记录总结
时间复杂度:O(n2)
循环一遍选择一个最大的数字与当前位置交换
代码
/**
* 选择排序
*/
public class SelectionSort {
public static void selectionSort(int[] arr) {
for (int i = 0; i < arr.length; i++) {
int flag = i;
for (int j = i; j < arr.length; j++) {
if (arr[j] > arr[flag]) {
flag = j;
}
}
swap(arr, flag, i);
}
}
public static void swap(int[] arr, int a, int b) {
int temp = arr[a];
arr[a] = arr[b];
arr[b] = temp;
}
public static void main(String[] args) {
//模拟数据
int[] array = {52,63,14,59,68,35,8,67,45,99};
System.out.println("原数组:");
for (int i : array) {
System.out.print(i+" ");
}
System.out.println();
selectionSort(array);
System.out.println("排序后:");
for (int i : array) {
System.out.print(i+" ");
}
}
}