您的位置:首页 > 其它

三种排序算法

2010-10-23 15:03 609 查看
如下,三种排序算法的代码:插入、冒泡和快排,而快排实际上是对冒泡的一种改进。等复习算法的分治时,再将归并排序算法发上来。

#include<iostream>
using namespace std;
//插入排序法,算法的时间复杂度为o(n*n),稳定的排序方法
void insertSort(int a[],int length)
{
for(int i=1;i<length;i++)
{
if(a[i-1]>a[i])
{
int temp=a[i];
int j;
for(j=i-1;j>=0;j--)
{
if(a[j]>temp)
{
a[j+1]=a[j];
}
else
{
break;
}
}
if(j==0)
{
a[j]=temp;
}
else
{
a[j+1]=temp;
}

}
}
cout<<"用插入排序法排好序为:/n";
for(int i=0;i<length;i++)
cout<<a[i]<<" ";
cout<<endl;
}
//用冒泡法进行排序,算法的时间复杂度为o(n*n) ,稳定的排序方法
void maopaoSort(int a[],int length)
{
for(int i=0;i<length-1;i++)
for(int j=0;j<length-1-i;j++)
{
if(a[j]>a[j+1])
{
int temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
cout<<"用冒泡排序法排好序为:/n";
for(int i=0;i<length;i++)
cout<<a[i]<<" ";
cout<<endl;
}
//快速排序,不稳定的排序,好的情况下时间复杂度为o(n*logn),坏的情况下时间复杂度为o(n*n)
int Partion(int a[],int low,int high)
{
int i=low,j=high+1;
int x=a[low];
while(true)
{
while(a[++i]<x&&i<j);
while(a[--j]>x);
if(i>=j)
break;
int temp=a[i];
a[i]=a[j];
a[j]=temp;
}
a[low]=a[j];
a[j]=x;
return j;
}
void QSort(int a[],int low,int high)
{
if(low<high)
{
int pivot=Partion(a,low,high);
QSort(a,low,pivot-1);
QSort(a,pivot+1,high);
}
}
int main()
{
int a[]={4,5,1,7,6};
insertSort(a,5);
int b[]={8,0,1,5,3};
maopaoSort(b,5);
int a1[]={3,4,-1,2,5,9};
QSort(a1,0,5);
for(int i=0;i<6;i++)
cout<<a1[i]<<" ";
cout<<endl;
system("pause");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  算法 pivot system