排序

来源:互联网 发布:新手效果图制作软件 编辑:程序博客网 时间:2024/06/05 15:54
#include "stdafx.h"#include<iostream>template<typename T>void swap_t(T& a, T& b){T t = a;a = b;b = t;}//-------------insert sort-------------------------template <typename T>void insert_sort(T* p, int len){for (int i = 0; i < len; ++i){T tm = p[i];int k = i;for (; k > 0; --k){if (tm >= p[k - 1]){break;}p[k] = p[k - 1];}p[k] = tm;}}//---------------------------------------------------//-------------bubble sort-------------------------template <typename T>void bubble_sort(T* p, int len){for (int i = 1; i < len; ++i){for (int k = len-1; k >= i; --k){if (p[k] < p [k-1]){swap_t(p[k], p[k - 1]);}}}}//---------------------------------------------------//---------------------------------------------------//-------------select sort-------------------------template <typename T>void select_sort(T* p, int len){for (int i = 0; i < len -1; ++i){int imin = i;for (int k = i + 1; k < len; ++k){if (p[imin] > p[k]){imin = k;}}if (imin != i){swap_t(p[imin], p[i]);}}}//---------------------------------------------------//------------------------quicksort------------------template<typename T>void quicksort(T* a, int lo, int hi){//  lo is the lower index, hi is the upper index  //  of the region of array a that is to be sorted  int i = lo, j = hi;// comparison element x  int x = a[(lo + hi) / 2];//  partition  do{while (a[i]<x) i++;while (a[j]>x) j--;if (i <= j){swap_t(a[i], a[j]);i++;j--;}} while (i <= j);//  recursion  if (lo < j)quicksort(a, lo, j);if (i < hi)quicksort(a, i, hi);}//---------------------------------------------------int _tmain(int argc, _TCHAR* argv[]){int aa[] = { 3, 1, 4,2};insert_sort(aa,4);//bubble_sort(aa,4);//select_sort(aa,4);//std::sort(aa, aa + 4, std::less<int>());for (auto i : aa){std::cout << i << std::endl;}}


0 0