POJ_随机快速排序

本文介绍了一段使用C++实现的快速排序算法,并详细解释了其中的随机数生成函数getp(l, r)的作用。通过实例演示,帮助读者理解排序算法的核心逻辑及其在实际编程中的应用。

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

#include<iostream>
#include<cmath>
#include<string>
#include<cstring>
#include<algorithm>
#include<cstdio>
using namespace std;
#define N 100010
int a[N] = {};
int getp( int l, int r){// 边界取等
	return l+rand()%(r-l+1);
	//return (l+r)/2;
}
void swap( int* c, int p, int q){
	int t = c[p];
	c[p] = c[q];
	c[q] = t;
}
int partition( int l, int r,int* b, int key){
	int first = l;
	int last = r;
	while( first < last ){
		while( first < last && b[first] < key )
			first++;
		if( first >= last)
			break;
		b[last] = b[first];
		last--;
		while( first < last && b[last] > key )
			last--;
		if( first >= last )
			break;
		b[first] = b[last];
		first++;
	}
	return first;
}
void myqsort( int left, int right, int*b ){
	if( left >= right) 
		return;
	int p = getp(left, right);
	int tmp = b[p];
	swap( b, p, right);
	int pos = partition( left , right, b, tmp);
	b[pos] = tmp;
	myqsort( left, pos-1,b);
	myqsort( pos+1, right, b);

}
int main(){
	int n;
	scanf("%d", &n);
	for( int i  = 0; i < n; ++i )
		scanf("%d", &a[i]);
	myqsort( 0, n-1, a);
	for( int i = 0; i < n; ++i )
		printf( "%d\n", a[i]);
	//printf("\n");
	//system("pause");
	return 0;
}


主要想记住随机数生成函数(代码中的getp(..))

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值