思路:递归版思想没啥好说的,主要是细节,左右指针移动需要注意。这次尝试写非递归版,想的有点复杂了,其实类似树的前序遍历,细节见代码。
import javafx.util.Pair;
import java.util.Arrays;
import java.util.LinkedList;
public class Main {
public static int[] nums = new int[]{2,8,7,4,9,3,1,6,5};
//递归版快速排序
// public static void quickSort(int left, int right){
// while(left >= right - 1){
// return;
// }
// int temp = nums[left];
// int L = left, R = right - 1;
// while(L <= R){
// while(L < R && nums[R] >= temp){
// R--;
// }
// if(L < R){
// nums[L++] = nums[R];
// }
// while(L < R && nums[L] <= temp){
// L++;
// }
// nums[R--] = nums[L];
// }
// nums[L] = temp;
// quickSort(left, L);
// quickSort(L+1, right);
// }
//非递归版快速排序
public static void quickSortByStack(int left, int right){
LinkedList<Pair> stack = new LinkedList<>();
//保存左右边界
stack.push(new Pair(left, right));
while(!stack.isEmpty()){
Pair pair = stack.pop();
left = (int)pair.getKey();
right = (int)pair.getValue();
if(left >= right - 1){
continue;
}
int temp = nums[left];
int L = left, R = right - 1;
//partition过程,注意细节
while(L <= R){
while(L < R && nums[R] >= temp){
R--;
}
if(L < R){
nums[L++] = nums[R];
}
while(L < R && nums[L] <= temp){
L++;
}
nums[R--] = nums[L];
}
nums[L] = temp;
//先入右边部分,再入左边部分
if(L < right - 1){
stack.push(new Pair(L + 1, right));
}
if(left < L - 1){
stack.push(new Pair(left, L));
}
}
}
public static void main(String[] args){
System.out.println("before sort:");
System.out.println(Arrays.toString(nums));
// quickSortByStack(0, nums.length);
// System.out.println("after qucik sort recursion:");
// System.out.println(Arrays.toString(nums));
quickSortByStack(0, nums.length);
System.out.println("after qucik sort:");
System.out.println(Arrays.toString(nums));
}
}