您的位置:首页 > 其它

冒泡排序、插入排序及快速排序

2013-04-07 22:14 183 查看
#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~5
void 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);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐