实现方案一
public void sort(int[] arr, int left, int right) {
if (left >= right)
return;
int base = arr[left];
int i = left;
int j = right;
while (i < j) {
//当arr[j]大于基准数据右指针向左移动,否则交换数据
while (i < j && arr[j] > base) j--;
arr[i] = arr[j];
//当arr[i]小于基准数据左指针向右移动,否则交换数据
while (i < j && arr[i] < base) i++;
arr[j] = arr[i];
}
arr[i] = base;
sort(arr, left, i-1);
sort(arr, i+1, right);
}
实现方案二
public void sort(int[] arr, int left, int right) {
if(left >= right)
return;
int base = arr[left];
int cmpIdx = left;
for (int i = left + 1; i <= right; i++) {
if (arr[i] > base)
continue;
//交换
cmpIdx++;
int tmp = arr[cmpIdx];
arr[cmpIdx] = arr[i];
arr[i] = tmp;
}
arr[left] = arr[cmpIdx];
arr[cmpIdx] = base;
sort_2(arr, left, cmpIdx - 1);
sort_2(arr, cmpIdx + 1, right);
}
实现方案三
public void sort_3(int[] arr, int left, int right) {
if (left >= right)
return;
int base = arr[left];
int l = left+1;
int r = right;
while (l < r) {
//移动右指针
while (l < r && arr[r] > base)
r--;
while (l < r && arr[l] < base)
l++;
//交换左右
int tmp = arr[r];
arr[r] = arr[l];
arr[l] = tmp;
}
if (arr[l] < base){
arr[left] = arr[l];
arr[l] = base;
}
sort_3(arr, left, l - 1);
sort_3(arr, l + 1, right);
}