Quick sort non-recursive implementation/good future written test programming questions

Write in front

The second question of a good future written test programming question

Fast sort non-recursive

Reference: Click on the link
Basic idea: The process when using recursive sorting is:

  • First select a datum element, put the elements smaller than the datum on the left side of the datum, and place the ones larger than the datum on the right side of the datum
  • Recursively sort the left and right sides of the moved array

That non-recursion is actually using an array to save the left and right boundaries of the sub-array to be sorted

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);

Guess you like

Origin blog.csdn.net/qq_31672701/article/details/108419372