有序度是數組中具備有序關係的元素對的個數算法
徹底有序的數組的有序度爲滿有序度,即n長度的數組滿有序度爲Cn² ,即n*(n-1)/2;數組
滿有序度-有序度= 逆序度spa
public class SortMain { public static void main(String[] args) { int[] arr = {4, 5, 6, 3, 2, 1}; //有序度爲3 ,滿序度爲C52 5*6/2=15 ,逆序度爲12 int count = 0; count = bubbleSort(arr); System.out.println(Arrays.toString(arr)); System.out.println("排序執行:" + count); } public static int bubbleSort(int[] arr) { int count = 0; for (int i = 0; i < arr.length; i++) { //當一次冒泡中再也不交換數據,則表示徹底有序,可隨時退出循環 boolean flag = false; for (int j = 1; j < arr.length - i; j++) { //比較j與i if (arr[j - 1] > arr[j]) { count++; swap(arr, j); flag = true; } } if (!flag) { break; } } return count; } private static void swap(int[] arr, int j) { int temp = arr[j]; arr[j] = arr[j - 1]; arr[j - 1] = temp; } }
冒泡排序的特色:code
public static int insertSort(int[] arr) { int count = 0;//每移動一次加一 for (int i = 1; i < arr.length; i++) { int temp = arr[i]; int j = i - 1; for (; j >= 0; j--) { if (temp < arr[j]) { count++; arr[j + 1] = arr[j]; } else { break; } } arr[j + 1] = temp; } return count; }
插入排序的特色:排序