低レベルの並べ替えアルゴリズム:バブルの並べ替え、
選択の並べ替え、
挿入の並べ替え(低レベルの並べ替えアルゴリズムで最速)、
高度な並べ替えアルゴリズム:クイック並べ替え、
マージ並べ替え、
ヒープの並べ替え
...
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;
}