冒泡排序、插入排序及快速排序
来源:互联网 发布:java的replace 编辑:程序博客网 时间:2024/06/06 00:19
#include <iostream>#include <vector>#include <ctime>#include <cstdlib>#include <algorithm>using namespace std;// 输出全部vector值void ListAll( const vector<int>& vList ){ vector<int>::const_iterator iter; int iLineCount = 0; for ( iter = vList.begin(); iter != vList.end(); iter++ ) { if ( ( iLineCount + 1) == vList.size()) { cout << *iter; } else { cout << *iter<<"|"; } iLineCount ++; if ( iLineCount % 5 == 0 ) { cout <<endl; } } cout <<endl;}// 初始化void vInit( vector<int> &cVector,int iCount,int iType ){ for ( int i = 0; i <= iCount; i++ ) { cVector.push_back( i ); } if ( iType == 1) { srand((unsigned) time(0)); random_shuffle(cVector.begin(), cVector.end()); }}// 基本冒泡排序void BubbleSort( vector<int> &cVector ){ size_t vSize = cVector.size(); for ( size_t i = 0; i < vSize - 1; i++) { bool bFlag = false; for ( size_t j = i + 1; j < vSize; j++ ) { if ( cVector.at(i) < cVector.at(j)) { std::swap(cVector[i],cVector[j]); bFlag = true; } } if ( !bFlag ) { break; } }}// 插入排序// 1)从第一个元素开始,可以认为是已经排序的// 2)取出下一个元素,在已排序的元素中从后向前扫描// 3)如果该元素大于新元素已排序,则向下移动// 4)重复3直到找到已可排序的// 5)将新元素插入到该位置// 6)重复 1~5void InsertSort( vector<int> &cVector ){ size_t nSize = cVector.size(); cout<<"nSize "<< nSize <<endl; for ( int i = 1; i < nSize; i++ ) { if ( cVector[i] < cVector[i - 1 ] ) { int temp = cVector[i]; int j; for ( j = i; j >0 && cVector[j -1] > temp; j-- ) { cVector[j] = cVector[j-1]; } cVector[j] = temp; } } }void QuickSort( vector<int>&cVector,int left,int right ){ if ( left < right ) { int index = ( left + right ) /2; int pivot = cVector[index]; int i = left - 1; int j = right + 1; while( true ) { while ( (cVector[++i] < pivot)) {} while ( (cVector[--j] > pivot) ) {} if ( i >= j) { break; } std::swap(cVector[i],cVector[j]); } QuickSort(cVector,left,i-1); QuickSort(cVector,j+1,right); } }int main(){ vector<int> vAvector;// 定义 // 初始化 vInit( vAvector,10,1); cout <<"Before bubble sort"<<endl; ListAll( vAvector ); /* cout<<"Beign Basic bubble soft "<<endl; BubbleSort(vAvector); ListAll( vAvector);*/ /* cout <<"Beign Insert Sort"<<endl; InsertSort(vAvector); ListAll( vAvector); system("pause");*/ cout<<"Begin Quick Sort"<<endl; QuickSort( vAvector,0,vAvector.size()-1); ListAll( vAvector); system("pause"); return (0);}