冒泡排序:相邻两个数比较,根据大小交换位置
C++代码:
/**
* name:冒泡排序
* time:15/8/12 15:00
* environment: ubuntu 14.04, sublime text 3
*/
#include <iostream>
#include <algorithm>
using namespace std;
/*
* 打印数组
*/
void printArray(int array[],int length)
{
for (int i = 0; i < length; ++i)
{
cout << array[i] << " ";
}
cout << endl;
}
/*
* 常规冒泡排序
*/
void bubbleSort(int array[],int length)
{
for (int i = 0; i < length; ++i)
{
for (int j = 0; j < length-1-i; ++j)
{
if(array[j] > array[j+1])
{
swap(array[j],array[j+1]); //交换位置
}
}
}
printArray(array,10);
}
/*
* 改进冒泡排序
* 设置哨兵
*/
void bubbleSort_sentry(int array[],int length)
{
bool temp;
for (int i = 0; i < length; ++i)
{
temp = false;
for (int j = 0; j < length-1-i; ++j)
{
if(array[j] > array[j+1])
{
swap(array[j],array[j+1]); //交换位置
temp = true;
}
}
if (!temp)
{
cout << i << endl;
break;
}
}
printArray(array,10);
}
/*
* 改进冒泡排序
* 双向冒泡
*/
void bubbleSort_two_way(int array[],int length)
{
int small = 0;
int big = length-1;
while(small < big)
{
for (int i = 0; i < small; ++i) //正向冒泡
{
if(array[i] > array[i+1])
{
swap(array[i],array[i+1]); //交换位置
}
}
small++;
for (int i = big; i > small; i--) //反向冒泡
{
if(array[i-1] > array[i])
{
swap(array[i],array[i-1]); //交换位置
}
}
big--;
}
}
int main()
{
int array[10] = {0,8,4,1,3,2,5,7,6,9};
bubbleSort(array,10);
int array2[10] = {0,8,4,1,3,2,5,7,6,9};
bubbleSort_sentry(array2,10);
int array3[10] = {0,8,4,1,3,2,5,7,6,9};
bubbleSort_two_way(array3,10);
printArray(array3,10);
return 0;
}
//结果:
//0 1 2 3 4 5 6 7 8 9
//3
//0 1 2 3 4 5 6 7 8 9
//0 1 2 3 4 8 5 6 7 9