Algoritmo de clasificación de bajo nivel: clasificación de burbujas, clasificación de
selección , clasificación de
inserción (el más rápido en el algoritmo de clasificación de bajo nivel),
algoritmos de clasificación avanzados: clasificación rápida,
clasificación de combinación,
clasificación de montón
...
1. Orden de selección
Demostración de animación:
#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. Orden de inserción
Demostración de animación:
#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;
}
Eficiencia de clasificación de inserción mejorada
#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;
}
Extensión: habilite un algoritmo de clasificación para clasificar diferentes tipos de datos
Utilice la plantilla de C ++, utilizando el algoritmo de ordenación por inserción como ejemplo:
#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;
}