选择排序(Selection Sort)的实现
思想如下:
- First,find the smallest element in the array,and exchange it with the element in the first position
- Then ,find the second smallest element in the array.and exchange it with the element in the second position
- continue in this way until the entire array is sorted
java 实现代码如下:
public class SelectionSort {
public static void main(String[] args) {
//选择排序的实现
int[] a={9,8,7,6,5,4,3,2,1,0};
System.out.println("排序前的数组如下:"+Arrays.toString(a));
int min;
for(int i=0;i<a.length-1;i++){
min=i;
int j=i+1;
for(;j<a.length;j++){//在数组中没有排序的部分中寻找的最小值
if(a[min]>a[j]){
min=j;
}
}
//每次循坏找到最小值后就与当前位置进行交换
swap(a,i,min);
}
System.out.println("排序后的数组如下:"+Arrays.toString(a));
}
public static void swap(int [] a,int i,int j){
int temp;
if(i!=j){
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
总结
- 选择排序至多会交换n次
- 选择排序的时间复杂度为O(n^2);
So, Selection sort can be useful when memory write is a costly operation.