原地快速排序的步骤如下:
1. 取序列中的任意值作为一个基准值;
2. 将该基准值与序列的头或者尾进行交换;
3. 将基准值之外的其他值与基准值进行比较,小于基准值的交换到序列前面,大于基准值的交换到序列后面;
4. 将基准值交换到序列的分界线处;
5. 将序列按基准值分为两部分分别进行快速排序;
代码如下:
private void quickSortInPlace(int[] s, int startIndex, int endIndex){
if(s == null || s.length < 2){
return;
}
if(startIndex >= endIndex || endIndex >= s.length || startIndex < 0){
return;
}
int pivot = s[startIndex];
int pivotIndex = startIndex;
swap(s, startIndex, endIndex);
for(int i=startIndex; i<endIndex; i++){
if(s[i] < pivot){
if(i != pivotIndex){
swap(s, i, pivotIndex);
}
pivotIndex++;
}else if(s[i] > pivot){
continue;
}
}
swap(s, pivotIndex, endIndex);
if(pivotIndex > startIndex+1){
quickSortInPlace(s, startIndex, pivotIndex-1);
}
if(pivotIndex < endIndex -1){
quickSortInPlace(s, pivotIndex+1, endIndex);
}
}
//将数组s中i和j的位置进行调换
private void swap(int[] s, int i, int j){
int temp = s[i];
s[i] = s[j];
s[j] = temp;
}