冒泡排序是一种很容易理解的排序算法,非常简单却又非常经典。在面试时出现的概率也非常高,甚至面试官会你让直接写出来,所以作为一个程序员,应该要做到随时随地都能写出这个算法来。
在网上可以找到很多关于冒泡排序的实现代码,但是有些经过了很多 的人的转载难免会有一些错误的出现,很少有人愿意去给新手写一个完整而又正确简洁的程序,反正我是深受其害。。。所以特意整理出三种用C++实现的方法以供参考。此处直接给出代码,至于冒泡排序的原理不再赘述。
#include <assert.h>
#include <iostream>
#include <conio.h>
using namespace std;
void BubbleSort1(int *pInt, int nLen);
void BubbleSort2(int *pInt, int nLen);
void BubbleSort3(int *pInt, int nLen);
int main()
{
int a[20], b[20]; //定义最多给20个数排序
int n = 0;
cout << "请输入你要排序的数字个数(最多20个):";
cin >> n;
if (n > 20)
{
n = 20;
}
for(int i = 0; i < n; i++)
{
cout << "请输入第" << i + 1 << "个数:";
cin >> b[i];
}
cout << endl;
do
{
for(int i = 0; i < n; i++)
{
a[i] = b[i];
}
int nIndex = 0;
cout << "请选择调用方法序号(1,2,3):";
cin >> nIndex;
if (nIndex != 1 && nIndex != 2 && nIndex != 3)
{
nIndex = 1;
}
if (nIndex == 1)
{
BubbleSort1(a, n);
}
else if (nIndex == 2)
{
BubbleSort2(a, n);
}
else
{
BubbleSort3(a, n);
}
cout << "你输入的" << n << "个数由小到大排序为:" <<endl;
for(int i = 0; i < n; i++)
{
cout<<a[i]<<" ";
}
cout << endl;
cout << "按q键退出,其他键继续" << endl;
cout << endl;
} while (getch() != 'q');
return 0;
}
void BubbleSort1(int *pInt, int nLen)
{
assert(pInt != NULL);
for (int i = 0; i < nLen - 1; i++)
{
for (int j = 0; j < nLen - 1 - i; j ++)
{
if (pInt[j] > pInt[j + 1])
{
int nTemp = pInt[j + 1];
pInt[j + 1] = pInt[j];
pInt[j] = nTemp;
}
}
}
}
void BubbleSort2(int *pInt, int nLen)
{
assert(pInt != NULL);
for (int i = nLen - 1; i > 0; i--)
{
for (int j = 0; j < i; j ++)
{
if (pInt[j] > pInt[j + 1])
{
int nTemp = pInt[j + 1];
pInt[j + 1] = pInt[j];
pInt[j] = nTemp;
}
}
}
}
void BubbleSort3(int *pInt, int nLen)
{
assert(pInt != NULL);
for (int i = 0; i < nLen - 1; i++)
{
for (int j = i + 1; j < nLen; j ++)
{
if (pInt[i] > pInt[j])
{
int nTemp = pInt[j];
pInt[j] = pInt[i];
pInt[i] = nTemp;
}
}
}
}
不论是哪一种方法,只要记住第一层循环变量 i 循环 nLen - 1 次,第二层循环变量 j 循环 nLen - 1 - i 次即可。