heapsort(Java)(最小堆)

 1 public static void main(String[] args)
 2 {
 3     Scanner input = new Scanner(System.in);
 4     int n = input.nextInt();
 5     int[] a = new int[n];
 6 
 7     a[0] = 0;  //不使用第一个位置
 8     for(int i = 1; i < a.length; i++)
 9         a[i] = (int)(Math.random() * 100);
10     //System.out.println(Arrays.toString(a));
11     long start = System.currentTimeMillis();
12     heapsort(a, a.length - 1);
13     long end = System.currentTimeMillis();
14     //System.out.println(Arrays.toString(a));
15     System.out.println(end - start);
16     //10000000个测试数据用时1050ms 100000000个测试数据用时11500ms
17 }
18 
19 public void static heapsort(int[] a, int n)
20 {
21     for(int i = n / 2; i >= 1; i--)
22     sink(a, i, n);
23     while(n > 1)
24     {
25     int temp = a[n];
26     a[n--] = a[1];
27     a[1] = temp;
28     sink(a, 1, n);
29     }
30 }
31 
32 public static void sink(int[] a, int k, int n)  //最小堆化
33 {
34     while(k <= n / 2)
35     {
36     int min_index = k * 2;
37     if(min_index + 1 <= n && a[min_index + 1] < a[min_index])
38         min_index++;
39     if(a[k] > a[min_index])
40     {
41         int temp = a[k];
42         a[k] = a[min_index];
43         a[min_index] = temp;
44         k = min_index;
45     }
46     else
47         break;
48     }
49 }

 

posted @ 2019-03-25 16:52  Huayra  阅读(381)  评论(0编辑  收藏  举报