for (int i = 0; i < MAXSIZE; i++) { arr[i] = new Random().nextInt(MAXSIZE); } System.out.println("修改前"); for (int i : arr) { System.out.print(i + " "); } System.out.println("");
new Quicksort().sortMethodOne(0, arr.length - 1); System.out.println("修改后"); for (int i : arr) { System.out.print(i + " "); } }
/** * * @param arr * 目标数组 * @param min * 排序的数组的起始位 * @param max * 排序的数组的结束位 */ privatevoidsortMethodOne(int min, int max){ // 一个临时变量,用于记录数组左边的位置 int left = min;
// 一个临时变量,用于记录数组右边的位置 int right = max;
// tempNumber很重要,用于记录初始点的数值,并在每次循环判断中将对应位置的值与之进行比较 int tempNumber = arr[left];
while (left < right) { // 第一步:先从右边向左遍历,找到一个比tempNumber小的数 while (left < right && arr[right] >= tempNumber) { right--; } // 找到后将arr[right]赋值给arr[left] arr[left] = arr[right];
// 第二步:从左向右遍历,找到一个比tempNumber大的数 while (left < right && arr[left] <= tempNumber) { left++; } // 找到后将arr[left]赋值给arr[right] arr[right] = arr[left]; }
// 中间数赋值 arr[left] = tempNumber;
// 遍历整理左边的数 if (left > min) { sortMethodOne(min, left - 1); }