网上抄来抄去的博客乱七八糟的太多了,标准的写法,实现一个partition函数和一个sort函数。
partition函数负责寻找每次的分割点,sort函数负责递归调用左右分段。
partition函数需要
- 传入一个初始选定的轴心下标,将其交换到数组末尾,
- 锚定一个分组下标(初始从最左边开始)
- 然后从数组左边到 [末尾-1] 的所有数字可以遍历一次来进行分组,
- 碰到比轴心值小的,就和锚定值交换,锚定下标往右移动,最后返回锚定的下标。
上层sort函数对返回的锚定下标进行左右分组的sort,就完成了。
附上一张无比清晰的gif(from wikipedia)
public static int partition(int[] nums, int left, int right) {
int storeIndex = left;
while (left < right) {
if (nums[left] <= nums[right]) {
swap(nums, left, storeIndex);
storeIndex ++;
}
left ++;
}
swap(nums, storeIndex, right);
return storeIndex;
}
public static void swap(int[] nums, int a, int b) {
int tmp = nums[a];
nums[a] = nums[b];
nums[b] = tmp;
}
public static void qSort(int[] nums, int low, int high) {
if (high > low) {
int storeIndex = partition(nums, low, high);
qSort(nums, low, storeIndex - 1);
qSort(nums, storeIndex + 1, high);
}
}