排序
public class Demo { public static void main(String[] args) { int [] arr = {5,6,1,4,3,2}; // int [] arr = {5,1,4,2,3}; int count = 0; for (int i = arr.length -1 ; i > 0 ; i--) { int max = arr[0]; int position = 0; //找出最大值和所在位置 for (int j = 1; j <= i; j++) { if(arr[j] > max){ max = arr[j]; position = j; } } //当前位置不是最大值,则需要交换 if(arr[i] != max){ //将最大值交换到排头位置 if(arr[0] != max){ arr[position] = arr[0]; arr[0] = max; count ++; } //将最大值放到正确的位置 arr[0] = arr[i]; arr[i] = max; count ++; } } for (int i = 0; i < arr.length; i++) { System.out.println(arr[i]); } System.out.println(count); } }