1101 Quick Sort (25 分)

该博客讨论了如何在不使用排序的情况下,通过比较原始序列和排序后的序列找到快速排序中的枢轴(pivot)候选元素。博主分析了快排过程,并提出了一种算法:首先对整个序列排序,然后逐个比较原序列中的元素与排序后的位置,当元素位置不变且大于已知最大值时,该元素可能是pivot。这种方法避免了对每个元素两侧的排序,提高了效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题意:

Input Specification:

Each input file contains one test case. For each case, the first line gives a positive integer N (≤10​5​​). Then the next line contains N distinct positive integers no larger than 10​9​​. The numbers in a line are separated by spaces.

Output Specification:

For each test case, output in the first line the number of pivot candidates. Then in the next line print these candidates in increasing order. There must be exactly 1 space between two adjacent numbers, and no extra space at the end of each line.

Sample Input:

5
1 3 2 4 5

Sample Output:

3
1 4 5

分析:

pivot:枢轴/中心点。其实pivot应该就是我们所说的快排中的 “哨兵”。快排中,任选一个元素为哨兵,然后对于其他的元素,小于哨兵的移动到哨兵的左边,大于的则挪到右边。

其实在这里,可以对于每一个元素左边和右边分别sort(),然后比较这个元素是否大于左边的最大值并且小于右边的最小值。但是这样做肯定会超时!!!所以必须换种思路。

我们可以先对整个序列sort(),然后把原序列的每一个元素与排序后的新序列进行比较:

1. 设一个变量max=0.

2.  1)比较排序前的元素和排序后元素的位置是否是一样的(快排的哨兵在一次快排后在序列中的位置和序列进行完整排序后是一致的呦~,因为哨兵大于它前的所有元素的最大值,且小于它后边所有元素的最小值!);  2)排序前的元素>max吗?如果 1)、2)都符合,则它可以是哨兵

3. 如果 循环到的 (未排序)序列的元素 > max,max=此元素~

代码:

#include<iostream>
#include<algorithm> 
#include<vector>
using namespace std;
int main(){
	int n,max=0,cnt=0;
	cin>>n;
	vector<int> v1(n),v2(n),v3;//int: -2147483648~2147483647
	for(int i=0;i<n;i++){
		cin>>v1[i];
		v2[i]=v1[i];
	}	
	sort(v2.begin(),v2.end());
	for(int i=0;i<n;i++){
		if(v1[i]==v2[i]&&v1[i]>max){
			cnt++;
			v3.push_back(v1[i]);
		}
		if(v1[i]>max) max=v1[i];
	}
	printf("%d\n",cnt);
	for(int i=0;i<cnt;i++){
		if(i>0) printf(" ");
		printf("%d",v3[i]);
	}
    cout<<endl;
	return 0;
} 

总结:

考点:快速排序,考察对快排的核心内容的理解

逻辑题

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值