您的位置:首页 > 其它

树形排序与堆排序

2017-03-19 15:55 489 查看
树形排序和堆排序隶属于选择类排序,前者又称为“锦标赛排序”,而后者则是前者的优化方案,由威洛姆斯于1964年提出。

树形排序的思想是将记录两两比较,选出较小者或较大者,然后在较小或较大者中再两两比较选出更小或更大者,以此类推,整个过程则呈现一种树形结构,其空间复杂度是较优的O(nlog2(n)),但额外产生了n-1个辅助空间。

为了减少辅助空间,降低空间复杂度,就出现了堆排序,其时间复杂度不变,而空间复杂度变为O(1).

树形排序

import java.util.Scanner;
public class TreeSort {

private static final int Length = 10;
private static int[] array = new int[2*Length-1];

public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
for(int i=0;i<array.length;i++){
if(i < Length-1) array[i] = 0;
else{
if(scanner.hasNextInt()) array[i] = scanner.nextInt();
}
}
scanner.close();
TreeSort treeSort = new TreeSort();
int count = Length;
while(count > 0){
treeSort.findSmall(0);  //查找较小者
treeSort.change(array[0]); //移除最小者
treeSort.clear();  //还原辅助空间
count--;
}
}

public void clear(){
for(int i=0;i<Length-1;i++) array[i] = 0;
}

public void change(int temp){
4000

System.out.print(temp+" ");
for(int i=array.length-1;i>=Length-1;i--){
if(temp == array[i]){
array[i] = Integer.MAX_VALUE;
break;
}
}
}

public void findSmall(int index){
if(array[2*index+1] == 0 && array[2*index+2] == 0){
findSmall(2*index+1);
findSmall(2*index+2);
}
array[index] = array[2*index+1] <= array[2*index+2] ? array[2*index+1] : array[2*index+2];
}

}


堆排序

import java.util.Scanner;
public class HeapSort {

private static final int Length = 10;
private static int[] array = new int[Length+1];

public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
for(int i=0;i<array.length-1;i++){
if(scanner.hasNextInt()) array[i] = scanner.nextInt();
}
scanner.close();
array[array.length-1] = Integer.MAX_VALUE;
HeapSort heapSort = new HeapSort();
int count = 10;
while(count > 0){
heapSort.findSmall(0); //查找最小者
heapSort.change();  //移除最小者
count--;
}
}

public void change(){
System.out.print(array[0]+" ");
array[0] = Integer.MAX_VALUE;
}

public void findSmall(int index){
if(2*(2*index+1)+1 < array.length){
findSmall(2*index+1);
findSmall(2*index+2);
}
int temp = array[index] < array[2*index+1] ? array[index] : array[2*index+1];
if(temp == array[2*index+1]){
array[2*index+1] = array[index];
array[index] = temp;
}
temp = array[index] < array[2*index+2] ? array[index] : array[2*index+2];
if(temp == array[2*index+2]){
array[2*index+2] = array[index];
array[index] = temp;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: