有序度是数组中具备有序关系的元素对的个数算法
彻底有序的数组的有序度为满有序度,即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; }
插入排序的特色:排序