您的位置:首页 > 其它

排序算法浅析——选择算法

2016-07-12 22:06 281 查看

选择算法

选择排序—简单选择算法(Selection sort)

算法描述

》每一次从待排序的数据元素中选出最小(或最大)的一个元素,存放在序列的起始位置,直到全部待排序的数据元素排完。即,先选出最小(或者最大)的一个数与第1个位置的数交换;然后在剩下的数当中再找最小(或者最大)的与第2个位置的数交换,依次类推,直到第n-1个元素(倒数第二个数)和第n个元素(最后一个数)比较为止。

》具体过程如下图所示:



算法分析

平均时间复杂度:O(n^2)

空间复杂度:O(1)

稳定性:不稳定

代码实现

public class SelectionSort {

public static int[] selection(int[] sort){

for(int i = 0; i < sort.length; i++){
int temp = sort[i];
int tempIndex = i;
for(int flag = i; flag < (sort.length - 1); flag++){
if(sort[flag + 1] < temp){
temp = sort[flag + 1];
tempIndex = flag + 1;
}

}
sort[tempIndex] = sort[i];
sort[i] = temp;
}

return sort;
}

public static void main(String[] args) {
int[] test = { 3, 1, 5, 7, 2, 4, 9, 6 };
int[] test2 = SelectionSort.selection(test);
for (int result : test2) {
System.out.print(result + " ");
}
}

}


堆排序(Heapsort)

算法描述

1)将初始待排序关键字序列(R1,R2….Rn)构建成大顶堆(小顶堆),此堆为初始的无序区;

2)将堆顶元素R[1]与最后一个元素R
交换,此时得到新的无序区(R1,R2,……Rn-1)和新的有序区(Rn),且满足R[1,2…n-1]<=R
;

3)由于交换后新的堆顶R[1]可能违反堆的性质,因此需要对当前无序区(R1,R2,……Rn-1)调整为新堆,然后再次将R[1]与无序区最后一个元素交换,得到新的无序区(R1,R2….Rn-2)和新的有序区(Rn-1,Rn)。不断重复此过程直到有序区的元素个数为n-1,则整个排序过程完成。

》具体过程如下:

若对数组{16,7,3,20,17,8}进行堆排序,先构建一个完全二叉树,



然后开始构建初始的大顶堆,从最后一个非叶子节点开始,







20和16交换后导致16不满足堆的性质,因此接着重新调整,



这样等到了初始堆,之后就开始进行排序。将20跟3交换,



这时又不满足堆,接着调整,





接着按照上述过程操作,

















算法分析

平均时间复杂度:O(N*logN)

空间复杂度:O(1)

稳定性:不稳定

代码实现

public class HeapSort {

public int heap[];
public int size;

public HeapSort(int[] heap){
this.heap = heap;
this.size = heap.length;
}

public void buildMaxHeap(){
for(int i = size/2-1; i >= 0; i--){
adjust(i);
}
}

public void adjust(int index){
int l = 2 * (index + 1) - 1; // 左孩子
int r = 2 * (index + 1); // 右孩子
int largest;

if(l < size && heap[l] > heap[index]){
largest = l;
} else {
largest = index;
}
if(r < size && heap[r] > heap[largest]) {
largest = r;
}

if(largest == index || largest > size){
return;
}

int temp = heap[index];
heap[index] = heap[largest];
heap[largest] = temp;
adjust(largest);
}

public void heap(){

for(int i = 0; i < heap.length; i++){
buildMaxHeap();
int temp = heap[0];
heap[0] = heap[size-1];
heap[size-1] = temp;
size--;
}
}

public static void main(String[] args) {
int[] test= { 3, 1, 5, 7, 2, 4, 9, 6 };
HeapSort hs = new HeapSort(test);
hs.heap();
for (int result : hs.heap) {
System.out.print(result + " ");
}
}
}


参考:

http://www.cnblogs.com/dolphin0520/archive/2011/10/06/2199741.html

http://www.360doc.com/content/14/0507/19/18042_375598267.shtml
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息