码迷,mamicode.com
首页 > 编程语言 > 详细

堆排序

时间:2015-08-03 12:54:33      阅读:152      评论:0      收藏:0      [点我收藏+]

标签:

public class HeapSort {
  /**
  * 堆排序
  *
  * @param args
  */

  public static void heapOne(int[] a, int n, int k) {
    int left = 2 * k + 1;
    int right = 2 * k + 2;

    int a1 = Integer.MAX_VALUE;
    int a2 = Integer.MAX_VALUE;

    if (left >= n && right >= n) return;
    if (left < n) a1 = a[left];
    if (right < n) a2 = a[right];
    if (a1 >= a[k] && a2 >= a[k]) return;

    if (a1 < a2) {
      int temp = a[k];
      a[k] = a[left];
      a[left] = temp;
      heapOne(a, n, left);
    } else {
      int temp = a[k];
      a[k] = a[right];
      a[right] = temp;
      heapOne(a, n, right);
    }

  }

  public static void heapSort(int[] array) {
  // 创建初始堆
    for (int i = ((array.length - 1) / 2); i >= 0; i--) {
      heapOne(array, array.length, i);
    }

    int n = array.length;

    while (n > 0) {
      System.out.print(array[0]);
      if (n > 1) {
        System.out.print(",");
      }
      array[0] = array[n - 1];
      n--;
      heapOne(array, n, 0);
    }
  }

  public static void main(String[] args) {
    // TODO Auto-generated method stub
    int[] a = { 38, 65, 97, 76, 13, 27, 49, 78, 34, 12, 64, 1 };
    heapSort(a);
  }

}

堆排序

标签:

原文地址:http://www.cnblogs.com/wllearnandroid/p/4699015.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!