算法导论第七章思考题7-2针对相同元素的快速排序-c++

本文介绍了一个改进版的快速排序算法实现,该算法通过分区过程来处理重复元素,并使用随机数生成器初始化数组以展示排序效果。文章提供了完整的C++代码实现,包括自定义的数据结构用于返回分区边界。

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

#include "stdafx.h"
#include <stdio.h>
#include <iostream>
#include <string>
#include <math.h>
#include <time.h>
using namespace std;
typedef struct Par_result
{
	int q;
	int t;
};
Par_result PARTITION(int a[],int p,int r)
{
	int x = a[r];
	int i = p - 1;
	int t = p - 1;
	for(int j=p;j<=r;j++)
	{
		if(a[j] < x)//or <=?
		{
			i++;
			t++;
			int  temp = a[t];
			if(t == j)
			{
				a[t] = a[i];
				a[i] = temp;
			}
			else
			{
				a[t] = a[i];
				a[i] = a[j];
				a[j] = temp;
			}
		}
		else if(a[j] == x)
		{
			t++;
			int temp = a[t];
			a[t] = a[j];
			a[j] = temp;
		}
	}
	Par_result par_result = {i,t};
	return par_result;
}

void quickSort(int a[],int p,int r)
{
	if(p<r)
	{
		Par_result par_result = PARTITION(a,p,r);
		quickSort(a,p,par_result.q);
		quickSort(a,par_result.t+1,r);
	}
}

int main()
{
	char s;
	//do{
		int a[10];
		//int a[10]= {1,4,5,6,4,2,7,4,8,4};
		//int a[10] = {   8   , 8   , 9 ,   5  ,  9 ,   9,    5,    4,    3,    2};
		srand(time(0));
		for(int i=0;i<10;i++)
		{
			a[i] = rand()%10;
			printf("%5d",a[i] );
		}	
		cout<<endl;
		quickSort(a,0,9);
		for(int i=0;i<10;i++)
			printf("%5d",a[i] );
		cout<<endl;
		cin>>s;
	//}while(s == 'y' || s == 'Y');
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值