选择排序也是最基本的排序算法之一,其算法复杂度为O(n^2),与待排序数组的内部结构没有关系。
算法简介
选择排序,顾名思义就是通过选择来排序。从一堆数中选出最小的放在第一位,在剩下的数中在选择最小的排在第二位。。。选择,就是一个比较的过程,从一堆数据中选择就是要在这个数据堆中一个一个进行比较。算法外层循环执行n次,每次一定进行i次比较操作,所以算法复杂度为n^2。非常直观的算法。
代码
package sorting;
public class Data {
/**
* generate an unsorted array of length n
* @param n length
* @param max the maximum integer element of this array
* @return an unsorted array consists of elements range from 1 to max
*/
public static int[] getArray(int n, int max){
int[] result = new int[n];
for(int i =0; i < n; i++){
result[i] = (int)(Math.random() * max + 1);
}
return result;
}
/**
* print the array
* @param arg array
*/
public static void printArray(int[] arg){
StringBuffer temp = new StringBuffer();
for(int i = 0; i < arg.length; i++){
temp.append(arg[i] + "\t");
}
System.out.println(temp);
}
}
package sorting;
public class SelectionSort {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
SelectionSort ss = new SelectionSort();
int[] data = Data.getArray(10, 100);
System.out.print("Source data:\t");
Data.printArray(data);
ss.selectionSort(data);
System.out.print("Sorted data:\t");
Data.printArray(data);
}
public void selectionSort(int[] arg){
int index = 0, min = 0, j = 0;
// why i < length -1?
// because when i equals length - 1, the rest of the array contains only 1 number.
// after this time of loop, arg[arg.length - 1]must be the minimum one
// in order to promote efficiency, wo should assign arg.length - 1 to a constant,
// and use this constant in the compare statement
for(int i = 0; i < arg.length - 1; i++){
index = i;
min = arg[i];
// find the minimal number in the rest of the array
for(j = i + 1; j < arg.length; j++){
if(arg[j] < min){
index = j;
min = arg[j];
}
}
//need switch
if(index != i){
arg[index] = arg[i];
arg[i] = min;
}
}
}
}

1952

被折叠的 条评论
为什么被折叠?



