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 }

 

转载于:https://www.cnblogs.com/Huayra/p/10594744.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值