#include<iostream>
#include<time.h>
#include<stdlib.h>//使用库函数srand和rand函数
using namespace std;
const int Max=10;
void Creat(int r[],int n);
void BubbleSort(int r[],int n);//起泡排序
int Partition(int r[],int first,int end) ;//一次划分
void QuickSort(int r[],int first ,int end);//快速排序
int main()
{
int a[Max+1]={0};
int b[Max+1]={0};
int i=0;
Creat(a,Max);
for(i=1;i<=Max;i++)//将数组a复制一份到数组b
b[i]=a[i];
cout<<"对于无序序列:";
for(i=1;i<=Max;i++)
cout<<b[i]<<" ";
cout<<endl;
BubbleSort(b,Max);
cout<<"执行起泡排序后,元素为:";
for(i=1;i<=Max;i++)
cout<<b[i]<<" ";
cout<<endl;
cout<<"对于无无序序列:";
for(i=1;i<=Max;i++)
cout<<a[i]<<" ";
cout<<endl;
QuickSort(a,1,Max);
cout<<"执行快速排序后,元素为:";
for(i=1;i<=Max;i++)
cout<<a[i]<<" ";
cout<<endl;
return 0;
}
void Creat(int r[],int n)
{
int i=0;
srand(time(NULL));
for(i=1;i<=n;i++)
r[i]=1+rand()%100;//待排序记录为两位数
}
void BubbleSort(int r[],int n)
{
int exchange=n;
int bound=n;
while(exchange!=0)
{
bound=exchange;
exchange=0;
int j;
for(j=1;j<bound;j++)
if(r[j]>r[j+1])
{
r[0]=r[j];
r[j]=r[j+1];
r[j+1]=r[0];
exchange=j;//记录每一次交换的位置
}
}
}
int Partition(int r[],int first,int end)
{
int i=first;
int j=end;//初始化
while(i<j)
{
while(i<j&&r[i]<=r[j])
j--;//右侧扫描
if(i<j)
{
r[0]=r[i];
r[i]=r[j];
r[j]=r[0];
i++;
}
while(i<j&&r[i]<=r[j])
i++;//左侧扫描
if(i<j)
{
r[0]=r[i];
r[i]=r[j];
r[j]=r[0];
j--;
}
}
return i;//i为轴记录的最终位置
}
void QuickSort(int r[],int first,int end)
{
if(first<end)
{
//区间长度大于一执行一次划分,否则递归结束
int pivot=Partition(r,first,end);
QuickSort(r,first,pivot-1);//递归对左侧子序列进行快速排序
QuickSort(r,pivot+1,end);//递归实现对右侧子序列的快速排序
}
}
数据结构 快速排序冒泡排序
猜你喜欢
转载自blog.csdn.net/qq_40270751/article/details/78867995
今日推荐
周排行