选择排序
分析:升序为例,遍历数组,记录最大数索引,最后和上次最后索引的数交换。
public class Test08 {
//选择排序
public static void selectionSort(int[] arr) {
for (int i = 1; i < arr.length; i++) {
int index = 0;
int lastIndex = arr.length - i;
for (int j = 1; j <= lastIndex; j++) {
if (arr[index] < arr[j]) {
index = j;
}
}
if (index != lastIndex) {
int temp = arr[lastIndex];
arr[lastIndex] = arr[index];
arr[index] = temp;
}
}
}
public static void main(String[] args) {
int[] arr = {20, 1, 82, 23, 13, 15, 0};
printArray(arr, "排序前:");
selectionSort(arr);
printArray(arr, "排序后:");
}
public static void printArray(int[] arr, String message) {
System.out.print(message);
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
}
}