2021.4.2美团 非递归快排
所有递归本质上就是用栈,把两边的边界确定,看什么时候入栈
面试不要急,想好再写,私底下写10来分钟不就写出来了
package lecode;
import java.util.*;
public class test
{
public static void main(String[] args) {
int[] nums = new int[]{5, 89, 36, 23, 11, 12, 11};
Deque<int[]> dq = new LinkedList<>();
dq.push(new int[]{0, nums.length-1});
while (!dq.isEmpty()){
int[] tmp = dq.pop();
int q = quicksort(nums, tmp[0], tmp[1]);
//想清楚啥时候入栈
if(tmp[0] < q-1) dq.push(new int[]{tmp[0], q-1});
if(q+1 < tmp[1]) dq.push(new int[]{q+1, tmp[1]});
}
for(int tmp : nums){
System.out.println(tmp);
}
}
//先写好一趟快排
public static int quicksort(int[] nums, int left, int right){
int i = left;
int j = right;
int target = nums[i];
while(i<j){
while (i<j && nums[j]>=target) j--;
while (i<j && nums[i]<=target) i++;
swap(nums, i, j);
}
swap(nums, left, i);
return i;
}
public static void swap(int[] nums, int i, int j){
int tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
}
}