排序-选择-java
1 public class Test { 2 public static void main(String[] args) { 3 int[] arr = {5, 2, 6, 8, 9, 1}; 4 if (arr == null || arr.length <= 2) { 5 return; 6 } 7 for (int i = 0; i < arr.length - 1; i++) { 8 //选择排序:主要是选择一个数,然后在整个数组里遍历取最大/最小,遍历完一轮就交换index,依此类推 9 int index = i; 10 for (int j = i + 1; j < arr.length; j++) { 11 index = arr[j] > arr[index] ? j : index; 12 } 13 swap(arr, i, index); 14 } 15 for (int i = 0; i < arr.length; i++) { 16 System.out.println(arr[i]); 17 } 18 } 19 20 private static void swap(int[] arr, int i, int j) { 21 int temp = arr[i]; 22 arr[i] = arr[j]; 23 arr[j] = temp; 24 } 25 }