public class HeapSort {
/**
* @描述:
* @方法名: sortHeap
* @param array
* @param start开始位置
* @param end结束位置
* @返回类型 void
* @创建人 lenovo
* @创建时间 2016-1-16下午8:42:55
* @修改人 lenovo
* @修改时间 2016-1-16下午8:42:55
*/
/*堆排序技巧:从最后元素建立大根堆;(createHeapandSort前半段)
* 每次交换最大元素跟当前堆,同时重新排堆,堆不断减少。(createHeapandSort后半段)
* sortHeap是用于建堆,此时堆处于除了start开始的元素都是满足大根堆的定义的。
*/
public static void sortHeap(int[] array, int start, int end)// 重新排序大根堆,只有第一个元素不满足堆的定义,需要将该元素不断下移。log(n)复杂度
{
int k = array[start];
int current_index = start;
int temp;
while (current_index <= end) {
if (2 * current_index + 1 > end)
break;
else if (2 * current_index + 2 > end)
temp = 2 * current_index + 1;// 没后续了
else {
if (array[2 * current_index + 1] >= array[2 * current_index + 2]) {
temp = 2 * current_index + 1;// 取较大的
} else {
temp = 2 * current_index + 2;
}
}// 这一步是用于定义temp
if (array[current_index] >= array[temp]) {
break;
} else {
change(array, current_index, temp);
current_index = temp;
}
}
}
private static void change(int[] array, int current_index, int temp) {
// TODO Auto-generated method stub
int w = array[current_index];
array[current_index] = array[temp];
array[temp] = w;
}
public static void createHeapandSort(int[] array)//先建立大根堆
{
for(int i=array.length-1;i>=0;i--)//倒着建堆
sortHeap(array,i,array.length-1);
for(int i=0;i<=array.length-1;i++)
{
change(array,0,array.length-1-i);//堆从后面越来越少了
sortHeap(array,0,array.length-1-i-1);
}
}
public static void main(String args[]) {
int a[] = new int[] { 7,2,4,5,3,1,8,99,10,21,2123,2212,12,212};
createHeapandSort(a);
for (int i = 0; i <= a.length - 1; i++)
System.out.println(a[i] + " ");
}
}
堆排序JAVA代码
最新推荐文章于 2023-04-24 11:37:55 发布