Java排序算法之冒泡排序
1、冒泡排序
/* *最原始排序 */ public static void sort(int array[]) { for (int i = 0; i < array.length - 1; i++) { for (int j = 0; j < array.length - 1 - i; j++) { if (array[j] > array[j + 1]) { int temp = array[j]; array[j] = array[j + 1]; array[j + 1] = temp; } } } } /* *利用标签进行改进 */ public static void sortV2(int array[]) { for (int i = 0; i < array.length - 1; i++) { boolean flag = true; for (int j = 0; j < array.length - 1 - i; j++) { if (array[j] > array[j + 1]) { int temp = array[j]; array[j] = array[j + 1]; array[j + 1] = temp; flag = false; } } if (flag) { break; } } } /* *利用标签和范围进行改进 */ public static void sortV3(int[] array) { int last = 0; int sorted = array.length - 1; for (int i = 0; i < array.length - 1; i++) { boolean flag = true; for (int j = 0; j < sorted; j++) { if (array[j] > array[j + 1]) { int temp = array[j]; array[j] = array[j + 1]; array[j + 1] = temp; flag = false; last = j; } } sorted = last; if (flag) { break; } } } /* *利用标签和奇偶循环进行改进,也称鸡尾酒排序 */ public static void sortV4(int[] array) { for (int i = 0; i < array.length / 2; i++) { boolean flag = true; for (int j = i; j < array.length - 1 - i; j++) { if (array[j] > array[j + 1]) { int temp = array[j]; array[j] = array[j + 1]; array[j + 1] = temp; flag = false; } } if (flag) { break; } flag = true; for (int j = array.length - 1 - i; j > i; j--) { if (array[j] < array[j - 1]) { int temp = array[j]; array[j] = array[j - 1]; array[j - 1] = temp; flag = false; } } if (flag) { break; } } }