冒泡排序、插入排序、快速排序

Deadly 提交于 2020-01-18 01:56:24

一、冒泡排序

#include<iostream>

using namespace std;

void bubble_sort(int a[],int len)

{

       int i,j,temp;

       int exchange=0;

       for(i=0;i<len;i++)

       {

              exchange=0;

              for(j=1;j<=len-i-1;j++)

              if(a[j-1]<a[j])

              {

                     temp=a[j-1];

                     a[j-1]=a[j];

                     a[j]=temp;

                     exchange=1;

              }

              if(exchange!=1)

                     return;

       }

}

int main()

{

       int a[]={7,3,5,8,9,1,2,4,6};

       bubble_sort(a,9);

       for(int i=0;i<9;i++)

              cout<<a[i]<<" " ;

       return 0;

}

 二、插入排序

#include<iostream>

using namespace std;

void insert_sort(int a[],int n)

{

       int i=0,j=0,temp=0;

       for(i=1;i<n;i++)

       {

              temp=a[i];

              for(j=i-1;temp<a[j]&&j>=0;j--)

                     a[j+1]=a[j];

              a[j+1]=temp;

       }

}

int main()

{

       int a[]={7,3,5,8,9};

       insert_sort(a,5);

       for(int i=0;i<5;i++)

              cout<<a[i]<<" " ;

       return 0;

}

三、快速排序

#include<iostream>

using namespace std;

void quick_sort(int a[],int low,int high)

{

       int i,j,pivot;

       if(low<high)

       {

              pivot=a[low];

              i=low;

              j=high;

              while(i<j)

              {

                     while(i<j && a[j]>=pivot)

                            j--;

                     if(i<j)

                            a[i++]=a[j];

                     while(i<j && a[i]<=pivot)

                            i++;

                     if(i<j)

                            a[j--]=a[i];

              }

              a[i]=pivot;

              quick_sort(a,low,i-1);

              quick_sort(a,i+1,high);

       }

}

int main()

{

       int data[9]={54,38,96,23,15,72,60,45,83};

       quick_sort(data,0,8);

       for(int i=0;i<9;i++)

              cout<<data[i]<<" " ;

       return 0;

}

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!