递归实现
public class Test {
public static void main(String[] args) {
int[] arr = {19, 8, 27, 6, 315, 14, 99, 34, 27};
quickSort(arr, 0, arr.length - 1);
for(int i=0;i<arr.length;i++){
System.out.println(arr[i]);
}
}
public static void quickSort(int[] arr, int left, int right) {
if (left >= right)
return;
int temp = arr[left];
int i = left, j = right;
while (i < j) {
while (i < j && arr[j] >= temp) {
j--;
}
while (i < j && arr[i] <= temp) {
i++;
}
if (i < j) {
int t = arr[i];
arr[i] = arr[j];
arr[j] = t;
}
}
arr[left] = arr[i];
arr[i] = temp;
quickSort(arr, left, i-1);
quickSort(arr, i+1, right);
}
}
非递归实现
递归的算法主要是在划分子区间,如果要非递归实现快排,只要使用一个栈来保存区间就可以了。
一般将递归程序改成非递归首先应该想到的就是使用栈,因为递归本身就是一个压栈弹栈的过程。
public class Test {
public static void main(String[] args) {
int[] arr = {19, 8, 27, 6, 315, 14, 99, 34, 27};
quickSortNotR(arr, 0 ,arr.length-1);
for(int i:arr){
System.out.println(i);
}
}
public static void quickSortNotR(int[] arr, int left, int right) {
if (left >= right)
return;
Stack<Integer> s = new Stack<>();
s.push(left);
s.push(right); //后入的right,所以要先拿right
while(!s.isEmpty()) //栈不为空
{
int r = s.pop();
int l = s.pop();
int index = partSort(arr,l,r);
if((index - 1) > l) //左子序列
{
s.push(l);
s.push(index - 1);
}
if((index + 1) < r) //右子序列
{
s.push(index + 1);
s.push(r);
}
}
}
// 分区内排序,这部分和递归排序逻辑一样
public static int partSort(int[] arr, int left, int right){
int temp = arr[left];
int i = left, j = right;
while (i < j) {
while (i < j && arr[j] >= temp) {
j--;
}
while (i < j && arr[i] <= temp) {
i++;
}
if (i < j) {
int t = arr[i];
arr[i] = arr[j];
arr[j] = t;
}
}
arr[left] = arr[i];
arr[i] = temp;
return i;
}
}