选择排序
选择排序(Selection sort)是一种简单直观的排序算法。它的工作原理是:第一次从待排序的数据元素中选出最小(或最大)的一个元素,存放在序列的起始位置,然后再从剩余的未排序元素中寻找到最小(大)元素,然后放到已排序的序列的末尾。以此类推,直到全部待排序的数据元素的个数为零。选择排序是不稳定的排序方法。
1:选择排序
首先在未排序序列中找到最小(大)元素,存放到排序序列的起始位置,然后,再从剩余未排序元素中继续寻找最小(大)元素,然后放到已排序序列的末尾。以此类推,直到所有元素均排序完毕。
选择排序-选择排序:
- 时间复杂度: O ( N 2 ) O(N^2) O(N2)
- 空间复杂度: O ( 1 ) O(1) O(1)
- 稳定性:不稳定
public class 选择排序 {
public static void main(String[] args) {
int [] array=new int[]{4,2,6,7,8,1,22,11,44,24,13};
func(array);
System.out.println(Arrays.toString(array));
}
//从小到大
private static void func(int[] array){
int minIndex;
int j;
int temp;
for(int i=0;i<array.length;i++){
minIndex=i;
j=i+1;
for(;j<array.length;j++){
if(array[j]<array[minIndex]){
minIndex=j;
}
}
temp=array[i];
array[i]=array[minIndex];
array[minIndex]=temp;
}
}
}
2:堆排序
堆排序(英语:Heapsort)是指利用堆这种数据结构所设计的一种排序算法。堆是一个近似完全二叉树的结构,并同时满足堆积的性质:即子结点的键值或索引总是小于(或者大于)它的父节点。
选择排序-堆排序:
- 时间复杂度: O ( N ∗ l o g 2 n ) O(N*log_2^n) O(N∗log2n)
- 空间复杂度: O ( 1 ) O(1) O(1)
- 稳定性:不稳定
public class 堆排序 {
public static void main(String[] args) {
int [] array=new int[]{4,2,6,7,8,1,22,11,44,24,13};
createHeap(array);
//因为需要从小到大排序,所以选择大根堆,每次将堆顶元素和最低元素互换位置
int end=array.length-1;
int temp;
while (end>0){
//交换堆顶和末尾元素
temp=array[0];
array[0]=array[end];
array[end]=temp;
//继续向下调整,不包含end
shiftDown(array,0,end);
end--;
}
System.out.println(Arrays.toString(array));
}
//这里是从小到大排序建立大根堆
private static void createHeap(int[] array){
//最大下标的父节点
int parent=(array.length-1-1)/2;
for(;parent>=0;parent--){
shiftDown(array, parent, array.length);
}
}
//向下调整
private static void shiftDown(int [] array,int parent,int length){
//左孩子
int child=parent*2+1;
int temp;
while (child<length){
//如果存在右孩子且右孩子比左孩子大 选择右孩子和父节点比较
if(child+1<length && array[child+1]>array[child]){
child=child+1;
}
if(array[child]>array[parent]){
temp=array[parent];
array[parent]=array[child];
array[child]=temp;
//继续向下走
parent=child;
child=parent*2+1;
}else {
break;
}
}
}
}