常用基本排序算法:选择,插入,冒泡,快排....
#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
int g_nCases = 0;
// 1 选择排序
template<class T>
void SelectedSort(T array[], const int n)
{
int nMiniIndex;
for(int i=0; i<n; i++){
nMiniIndex = i;
for(int j=i+1; j<n; j++){
if(array[nMiniIndex]>array[j]){
nMiniIndex = j;
}
}
if(nMiniIndex!=i){
swap(array[nMiniIndex], array[i]);
}
}
}
// 2
template<class T>
void printArray(T array[], int const n)
{
cout<<"Case "<<g_nCases++<<" :"<<endl;
for(int i=0; i<n; i++)
cout<<array[i]<<", ";
cout<<endl;
}
// 3 插入排序
template<class T>
void insertedSort(T array[], int const n)
{
T tempInsert;
int j;
for(int i=1; i<n; i++){
tempInsert = array[i];
for(j=i-1; j>=0; j--){
if(tempInsert<array[j]){
array[j+1] = array[j];
}else
break;
}
array[j+1] = tempInsert;
}
}
// 4 冒泡
template<class T>
void ballSort(T array[], int const n)
{
for(int i=0; i<n-1; i++){
bool flag = true;
for(int j=0; j<n-i-1; j++){
// 大者上浮
if(array[j]>array[j+1]){
swap(array[j], array[j+1]);
flag = false;
}
}
if(flag){
break;
}
}
}
// 5 快速排序
template<typename T>
void quickSort(T array[], int start, int const end)
{
if(start>=end)
return;
int provd = array[start];
int i = start, j = end;
while(i<j){
// 右端
while(i<j &&array[j]>=provd){
j--;
}
array[i] = array[j];
while(i<j &&array[i]<=provd){
i++;
}
array[j] = array[i];
}
array[j] = provd;
quickSort(array, start, j-1);
quickSort(array, j+1, end);
}
int main(int argc, char *argv[])
{
srand((unsigned)time(NULL));
const int N = 1000;
int array[N];
// Init
for(int i=0; i<N; i++){
array[i] = rand()%N;
}
printArray(array, N);
quickSort(array,0, N-1);
printArray(array, N);
return 0;
}