基本思想为每一趟从待排序的数据元素中选择最小(或最大)的一个元素作为首元素,直到所有元素排完为止。
public class SelectionSort {
private int[] array;
private int nElements;
public SelectionSort(int max) {
this.array = new int[max];
}
public void insert(int element) {
array[nElements] = element;
nElements ++;
}
public void selectionSort() {
int min;
for(int i = 0 ; i < nElements ; i ++) {
min = i;
for(int j = i + 1 ; j < nElements ; j ++) {
if(array[min] > array[j]) {
min = j;
}
}
swap(i, min);
}
}
private void swap(int left, int right) {
int temp = array[left];
array[left] = array[right];
array[right] = temp;
}
public int[] getArray() {
return array;
}
public static void main(String[] args) {
SelectionSort selectionSort = new SelectionSort(5);
selectionSort.insert(4);
selectionSort.insert(3);
selectionSort.insert(5);
selectionSort.insert(2);
selectionSort.insert(1);
selectionSort.selectionSort();
for(int i : selectionSort.getArray()) {
System.out.println("i:" + i);
}
}
}
参考:
《Java数据结构与算法》