[java]代码库
package selectionSort;
public class SelectionSortImpl {
/*
* 每一趟从待排序的数据元素中选出最小(或最大)的一个元素,顺序放在已排好序的数列的最后,直到全部待排序的数据元素排完。 选择排序是不稳定的排序方法
*/
public static int[] selectionSort(int[] arr) {
int len = arr.length;
int temp = Integer.MAX_VALUE;
int idx = -1;
for (int j = 0; j < len; j++) {
for (int i = j; i < len; i++) {
if (i == j) {
temp = arr[i];
idx = i;
} else if (arr[i] < temp) {
temp = arr[i];
idx = i;
}
}
/*
* every time put the smallest element in the sorted order list via
* exchanging the the first unsorted element with the mark smallest
* element
*/
if (idx != j) {
arr[idx] = arr[j];
arr[j] = temp;
}
}
return arr;
}
}
package selectionSort;
import java.util.Arrays;
public class TestSelectionSort {
public static void main(String[] args) {
int[] arr = new int[] { 9, 8, 7, 6, 5, 4, 2, 1 };
System.out.println("The unsorted array is : "
+ Arrays.toString(arr));
System.out.println("The sorted array with bubble sort algorithm is : "
+ Arrays.toString(SelectionSortImpl.selectionSort(arr)));
}
}
/*运行结果
The unsorted array is : [9, 8, 7, 6, 5, 4, 2, 1]
The sorted array with selection sort algorithm is : [1, 2, 4, 5, 6, 7, 8, 9]
*/