首页 > 代码库 > 几种排序

几种排序

1.冒泡:

#include<cmath>#include<cstdlib>#include<ctime>#include<iostream>using namespace std;int main(){    int n;    cout<<"INPUT NUM"<<endl;    cin>>n;    const int cn=n;    int num[cn],        srand(static_cast<unsigned>(time(NULL)));    for(auto &s:num)    {        s=rand()%100;    }    for(auto s:num)        cout<<s<<" ";    cout<<endl;    for(int i=0; i<cn; i++)    {        for(int j=0; j<cn-i; j++)        {            if(num[j]>num[j+1])            {                int temp=num[j];                num[j]=num[j+1];                num[j+1]=temp;            }        }    }    for(auto s:num)        cout<<s<<" ";    cout<<endl;    return 0;}

2.快速

 1 #include<iostream> 2 #include<cstdlib> 3 #include<ctime> 4 using namespace std; 5 /* 6 @快序排列算法的实现 7 */ 8 int partition(int data[],int m,int p)///返回p,使得data[p]是第p小的值 9 {10     int i=m,j=data[i];///j是划分元素11     bool flag=true;12     while(flag)13     {14         do15             i++;16         while(data[i]<j);17         do18             p--;19         while(data[p]>j);20         if(i<p)21         {22             int temp;23             temp=data[i];24             data[i]=data[p];25             data[p]=temp;26         }27         else28             flag=false;29     }30     data[m]=data[p];31     data[p]=j;32     return p;33 }34 void quicksort(int data[],int low,int high)35 {36     if(low<high)37     {38         int temp=high+1;39         temp=partition(data,low,temp);40         quicksort(data,low,temp-1);41         quicksort(data,temp+1,high);42     }43 }44 int main()45 {46 /*47 @产生一个规模为CNT的,范围为[RANDMIN,RANDMAX)的随机数组,并显示48 */49     int cnt,randmin,randmax;50     cout<<"Please Input ‘CNT‘ ‘RANDMIN‘ ‘RANDMAX‘"<<endl;51     cin>>cnt>>randmin>>randmax;52     const int CNT=cnt,53               RANDMIN=randmin,54               RANDMAX=randmax;55     int Data[CNT];56     srand((unsigned)time(NULL));57     for(int i=0; i<CNT; i++)58         Data[i]=RANDMIN+rand()%(RANDMAX-RANDMIN);59     cout<<"Before Change,Data=http://www.mamicode.com/"<<endl;60     for(int i=0; i<CNT; i++)61         cout<<Data[i]<<"    ";62     cout<<endl;63 /*64 @将数组用快速排序算法排序,并显示65 */66     quicksort(Data,0,CNT-1);67     cout<<"After Change,Data=http://www.mamicode.com/"<<endl;68     for(int i=0; i<CNT; i++)69         cout<<Data[i]<<"    ";70     cout<<endl;71     return 0;72 }

 

几种排序