`

堆排序

J# 
阅读更多
package math;

public class HeapSort1 {

public static void main(String[] args) {
int[] a = { 26, 5, 77, 1, 61, 11, 59, 15, 48, 19 };

Sort(a);
}

public static void Sort(int[] a) {
int n = a.length;
int temp = 0;

Display(a, "Before sort : ");

for (int i = n / 2; i > 0; i--){
Adjust(a, i - 1, n);
    Display(a, "建立大根堆 : ");
}
print.p("---------------------------------------");
for (int i = n - 2; i >= 0; i--) {
temp = a[i + 1];
a[i + 1] = a[0];
a[0] = temp;

Adjust(a, 0, i + 1);
Display(a, "重建立大根堆 : ");
}

Display(a, "After  sort : ");
}

public static void Adjust(int[] a, int i, int n) {
int j = 0;
int temp = 0;

temp = a[i];
j = 2 * i + 1;

while (j <= n - 1) {
if (j < n - 1 && a[j] < a[j + 1])
j++;

if (temp >= a[j])
break;

a[(j - 1) / 2] = a[j];

j = 2 * j + 1;
}

a[(j - 1) / 2] = temp;
}

public static void Display(int[] a, String str) {
System.out.println(str);

for (int i = 0; i < a.length; i++)
System.out.print(a[i] + " ");

System.out.println();
}
}


运行结果:


Before sort :
26 5 77 1 61 11 59 15 48 19
建立大根堆 :
26 5 77 1 61 11 59 15 48 19
建立大根堆 :
26 5 77 48 61 11 59 15 1 19
建立大根堆 :
26 5 77 48 61 11 59 15 1 19
建立大根堆 :
26 61 77 48 19 11 59 15 1 5
建立大根堆 :
77 61 59 48 19 11 26 15 1 5
---------------------------------------
重建立大根堆 :
61 48 59 15 19 11 26 5 1 77
重建立大根堆 :
59 48 26 15 19 11 1 5 61 77
重建立大根堆 :
48 19 26 15 5 11 1 59 61 77
重建立大根堆 :
26 19 11 15 5 1 48 59 61 77
重建立大根堆 :
19 15 11 1 5 26 48 59 61 77
重建立大根堆 :
15 5 11 1 19 26 48 59 61 77
重建立大根堆 :
11 5 1 15 19 26 48 59 61 77
重建立大根堆 :
5 1 11 15 19 26 48 59 61 77
重建立大根堆 :
1 5 11 15 19 26 48 59 61 77
After  sort :
1 5 11 15 19 26 48 59 61 77
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics