排序算法[ 选择,插入,冒泡,快排 ]

 

常用基本排序算法:选择,插入,冒泡,快排....

#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;  
}

转载于:https://my.oschina.net/ScottYang/blog/59701

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值