1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
| package fg;
public class QuickSort{ private static int count;
/** * 快速排序 * * @param num 排序的数组 * @param left 数组的前针 * @param right 数组后针 */ private static void QuickSort (int[] num, int left, int right) { //如果left等于right,即数组只有一个元素,直接返回 if (left >= right) { return; } //设置最左边的元素为基准值(key) int key = num[left]; //数组中比key小的放在左边,比key大的放在右边,key值下标为i int i = left; int j = right; while (i < j) { //j向左移,直到遇到比key小的值 while (num[j] >= key && i < j) { j--; } //i向右移,直到遇到比key大的值 while (num[i] <= key && i < j) { i++; } //i和j指向的元素交换(i<j情况) if (i < j) { int temp = num[i]; num[i] = num[j]; num[j] = temp; } } num[left] = num[i]; num[i] = key; count++; QuickSort(num, left, i - 1); QuickSort(num, i + 1, right); }
/** * 将一个int类型数组转化为字符串 * * @param arr * @param flag * @return */
//遍历一下数组而已 private static String arrayToString (int[] arr, String flag) { String str = "数组为(" + flag + "):"; for (int a : arr) { str += a + "\t"; } return str; }
/** * 测试 * * @param args */ public static void main (String[] args) { int[] num = {3, 44, 38, 64, 52, 11, 64, 55, 99, 11, 18,59,8989,54,12,544,6,154,4,7,454,245,45,61,64}; System.out.println(arrayToString(num, "未排序")); QuickSort(num, 0, num.length - 1); System.out.println(arrayToString(num, "排序")); System.out.println("数组个数:" + num.length); System.out.println("循环次数:" + count);
} }
|