快速排序非递归实现/好未来笔试编程题

写在前面

好未来的笔试编程题的第二题

快排非递归

参考:点击链接
基本思想:在利用递归排序时的流程是:

  • 先选一个基准元素,将小于基准元素的放在基准的左面,大于基准元素的放在基准的右面
  • 对移动好的数组的左边和右边分别递归排序

那非递归其实就是利用数组保存待排序的子数组的左右边界

vector<int> nums;//存放未排序的数组huafen

//划分
int Partition(int left, int right){
    
    
	int flag = nums[left];
	
	while(left < right){
    
    
		while(left < right && nums[right] >= flag)
			--right;
		nums[left] = nums[right];
		while(left < right && nums[left] <= flag){
    
    
			++left;
		}
		nums[right] = nums[left];
	}
	nums[left] = flag;
	return left;
}

//非递归快排
void QuickSort(int left, int right){
    
    
	//借助栈,保存待排序子数组的边界
	stack<int> s;
	if(left < right){
    
    
		int bound = Partition(left, right);
		if(bound - 1 > left){
    
    //左半部分的边界入栈
			s.push(left);//左边界入栈
			s.push(bound - 1);//右边界入栈
		}
		if(bound + 1 < right){
    
    //右半部分的边界入栈
			s.push(bound + 1);
			s.push(right);
		}
		while(!s.empty()){
    
    //栈非空时,子数组快排
			int rb = s.top();
			s.pop();
			int lb = s.top();
			s.pop();
			bound = Partition(lb, rb);
			if(bound - 1 > lb){
    
    
				s.push(lb);
				s.push(bound - 1);
			}
			if(bound + 1 < rb){
    
    
				s.push(bound + 1);
				s.push(rb);
			}
		}
	}
}

//调用
QuickSort(0, nums.size() - 1);

猜你喜欢

转载自blog.csdn.net/qq_31672701/article/details/108419372