低级排序算法:冒泡排序
选择排序
插入排序(在低级排序算法最快)
高级排序算法:快速排序
归并排序
堆排序
……
1、选择排序
动图演示:
#include <iostream>
using namespace std;
void selectionSort(int a[], int len)
{
int i, j, m;
for(i=0; i<len-1; i++)
{
m=i;
for(j=i+1; j<len; j++)
{
if(a[j]<a[m])
m=j;
}
swap(a[i],a[m]);
}
}
int main()
{
int i;
int a[10]={
1,3,5,7,9,0,2,4,6,8};
int len = sizeof(a)/sizeof(a[0]);
selectionSort(a, len);
for(i=0; i<len; i++)
cout << a[i] << endl;
return 0;
}
2、插入排序
动图演示:
#include <iostream>
using namespace std;
void InsertSort(int *a, int n)
{
int out;
int temp;
//把数据分成两组,1--排好顺序,2--未排好序,开始时,1组中只有第一个数据,2组中是剩余数据。
//1组在屋外,2组在屋内。2组中的数据一个一个地出来,每出来一个数据就从后向前与1组中的数据比较,直到找到一个小于本身地数据,插入到它后面(插入前,需将大于本身的数据后移)
for(out=1; out<n; out++)
{
temp = a[out];
while(out>0 && a[out-1]>temp)
{
a[out]=a[out-1];
out--;
}
a[out]=temp;
}
}
int main()
{
int i;
int len;
int a[]={
1,3,5,7,9,2,4,6,8};
len=sizeof(a)/sizeof(a[0]);
InsertSort(a,sizeof(a)/sizeof(a[0]));
for(i=0; i<len; i++)
{
cout<< a[i] << " ";
}
cout<<endl;
return 0;
}
插入排序效率提高
#include <iostream>
using namespace std;
template<class T>
void InsertSort(T *a, int n)
{
T temp;
int i, j;
for(j=2; j<n; j++)
{
temp=a[j];
a[0]=temp;
i=j-1;
while(temp < a[i])
{
a[i+1]=a[i];
i--;
}
a[i+1]=temp;
}
}
int main()
{
int i;
int len;
//a[0]不参与排序
float a[]={
0, 1, 3.4, 5, 7.2, 9, 2, 4.1, 6, 8};
len=sizeof(a)/sizeof(a[0]);
InsertSort(a,sizeof(a)/sizeof(a[0]));
for(i=1; i<len; i++)
{
cout<< a[i] << endl;
}
cout<<endl;
return 0;
}
拓展:使一个排序算法能够对不同类型的数据排序
使用C++模板,使用以插入排序算法为例:
#include <iostream>
using namespace std;
template<class T>
void InsertSort(T *a, int n)
{
T temp;
int out;
for(out=1; out<n; out++)
{
temp=a[out];
while(out>0 && a[out-1]>temp)
{
a[out]=a[out-1];
out--;
}
a[out]=temp;
}
}
int main()
{
int i;
int len;
float a[]={
1, 3.4, 5, 7.2, 9, 2, 4.1, 6, 8};
len=sizeof(a)/sizeof(a[0]);
InsertSort(a,sizeof(a)/sizeof(a[0]));
for(i=0; i<len; i++)
{
cout<< a[i] << endl;
}
cout<<endl;
return 0;
}