(冒泡,选择,插入,归并,堆排)排序算法

来源:互联网 发布:mac图片查看器 编辑:程序博客网 时间:2024/06/15 17:57


冒泡排序:每次把数组中最大的数字沉入数组的最低处;时间复杂度是O(n^2);

#include<iostream>
using namespace std;
int main()
{
int a[]={2,1,4,6,9,0,55};
int n = sizeof(a)/sizeof(int);
for(int i =0;i<n;++i)//这个控制的是趟数
{
for(int j =0;j+i<n-1;++j)//这个控制的是次数
{
if(a[j]>a[j+1])
{
int temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
}
for(int i =0;i<n;++i)
{
printf("%d ",a[i]);
}
return 0;
}

快速排序:

快速排序的思想:

(1)选取一个基准元素(一般选取最开头或者最末尾)

(2)进行一趟排序,把记录分为俩个模块,左边这个记录是比都比基准元素小,右边这个基准元素都比大;

(3)基准元素就到了排好元素的位置;

(4)分别对这俩个模块用相同的方法递归排序,直到所有的数字有序;

#include<iostream>
using namespace std;
void swap(int & n,int &m)
{
int temp= n;
n = m;
m = temp;
}
int Partion(int a[],int low,int high)
{
int key = a[low];
while(low <high)
{
while(low < high && a[high] >= key)--high;
swap(a[low],a[high]);
while(low<high && a[low] <= key)++low;
swap(a[low],a[high]);
}
return low;
}
void QuickSort(int a[],int n,int m)
{
if(n<m)
{
int  p = Partion(a,n,m);
QuickSort(a,n,p-1);
QuickSort(a,p+1,m);
}
}
int main()
{
int a[]={2,1,4,6,9,0,55};
int n = sizeof(a)/sizeof(int);
int low =0;
int high = n-1;
    QuickSort(a,0,n-1);
for(int i =0;i<n;++i)
{
cout<<a[i]<<" ";
}
return 0;
}

插入排序:

1.直接插入排序

2.折半插入排序

3.希尔排序

void InsertSort(int a[],int left,int right)
{
int i,j;
for(i = left+1;i<right;++i)
{
if(a[i]<a[i-1])
{
int temp =a[i];
j = i-1;
do{
a[j+1]=a[j];
--j;
}while(a[j] >temp && j>=left);
a[j+1]= temp;
}
}
}

阅读全文
0 0
原创粉丝点击