您的位置:首页 > 其它

排序算法一:冒泡排序

2015-02-04 20:40 113 查看
1:基本原理

从后往前,依次比较相邻的两个数,将大数放在前面,小数放在后面

2:算法记法

外循环(i = 1, i < count):需要执行的趟数(n - 1)

内循环(j = count -1, j >= i):每趟需要比较的次数(n - 1)

3:算法实现

#include <iostream>

using namespace std;
typedef int dt;

void bubbleSort(dt *pdata, int count) {
dt temp;
for(int i = 1; i < count; ++i) {
for(int j = count -1; j >= i; --j) {
if (pdata[j] > pdata[j - 1]) {
temp = pdata[j];
pdata[j] = pdata[j - 1];
pdata[j - 1] = temp;
}
}
}
}

int main(int argc, char *argv[]) {
int array[5] = {5,3,4,1,2};
cout << "_____before sort_____ " << endl;
for (int i = 0; i < 5; ++i) {
cout << array[i] << endl;
}

bubbleSort(array, 5);
cout << "_____after sort_____ " << endl;
for (int i = 0; i < 5; ++i) {
cout << array[i] << endl;
}

system("pause");

return 0;
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: