void quickSortNonRecursive(int arr[],int left,int right){
//通过栈实现
Stack<Integer> stack=new Stack<>();
stack.push(left);
stack.push(right);
while(!stack.isEmpty()){
int rightNew=stack.peek();
stack.pop();
int leftNew=stack.peek();
stack.pop();
//获取排序轴索引,该索引本身不再参与排序
int middle=partion2(arr,leftNew,rightNew);
if(middle-1>leftNew){
stack.push(left);
stack.push(middle-1);
}
if(middle+1<rightNew){
stack.push(middle+1);
stack.push(rightNew);
}
}
}
public int partion2(int []nums, int left, int right) {//第二种partion的写法
int i = left, j = right + 1;
int pivot = nums[left];
while (i < j) {
while (i < right && nums[++i] < pivot);
while (j > left && nums[--j] > pivot);
if (i >= j) {
break;
}
swap(nums, i,j);
}
swap(nums,left,j);
return j;
}
private void swap(int [] nums,int i, int j) {
// TODO Auto-generated method stub
int temp ;
temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
快速排序的循环实现
最新推荐文章于 2023-07-18 17:23:34 发布