冒泡排序适用于 数组中个数10以内的情况
快速排序适用于 数组中个数10以外的情况
package cango.scf.com; import java.util.*; public class Sort { public static void main(String[] args) { int[] intArr = new int[10]; Random ra = new Random(); for (int i = 0; i < 10; i++) { intArr[i] = ra.nextInt(100) + 1; } System.out.println("排序前:"); for (int i = 0; i < intArr.length; i++) { System.out.print(intArr[i] + ","); } //获取当前时间为开始时间,转换为long型 long startTime = System.nanoTime(); // 纳秒 if (0 + 10 >= intArr.length) { //冒泡排序 bubble(intArr); } else { //快速排序 quickSort(intArr, 0, intArr.length - 1); } //获取当前时间为截止时间,转换为long型 long stopTime = System.nanoTime(); // 纳秒 //计算时间差,单位毫秒 long timeSpan = stopTime - startTime; System.out.println(); System.out.println("排序执行了 " + timeSpan + " 納秒"); System.out.println("排序后:----------------------"); for (int i = 0; i < intArr.length; i++) { System.out.print(intArr[i] + ","); } System.out.println(); } /** * 冒泡排序 10位長度以內的數組 */ private static void bubble(int[] arr) { for (int i = 0; i < arr.length - 1; i++) {//外层循环控制排序趟数 for (int j = 0; j < arr.length - 1 - i; j++) {//内层循环控制每一趟排序多少次 if (arr[j] > arr[j + 1]) { int temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } } /** * 快速排序 10位長度以上的數組 * * @param arr * @param startIndex * @param endIndex */ public static void quickSort(int[] arr, int startIndex, int endIndex) { // 递归结束条件:startIndex大等于endIndex的时候 if (startIndex >= endIndex) { return; } // 得到基准元素位置 int pivotIndex = partition(arr, startIndex, endIndex); // 用分治法递归数列的两部分 quickSort(arr, startIndex, pivotIndex - 1); quickSort(arr, pivotIndex + 1, endIndex); } private static int partition(int[] arr, int startIndex, int endIndex) { // 取第一个位置的元素作为基准元素 int pivot = arr[startIndex]; int left = startIndex; int right = endIndex; // 坑的位置,初始等于pivot的位置 int index = startIndex; //大循环在左右指针重合或者交错时结束 while (right >= left) { //right指针从右向左进行比较 while (right >= left) { if (arr[right] < pivot) { arr[left] = arr[right]; index = right; left++; break; } right--; } //left指针从左向右进行比较 while (right >= left) { if (arr[left] > pivot) { arr[right] = arr[left]; index = left; right--; break; } left++; } } arr[index] = pivot; return index; } }