您的位置:首页 > 理论基础 > 数据结构算法

数据结构 - 冒泡排序(Bubble Sort) 详解 及 代码(C++)

2014-04-24 17:32 771 查看

冒泡排序(Bubble Sort) 详解 及 代码(C++)

本文地址: http://blog.csdn.net/caroline_wendy/article/details/24425437

冒泡排序(Bubble Sort): 是一种交换排序, 每次交换相邻元素的位置, 则需要确定的值, 会上升至序列末尾.

然后, 末尾的值固定, 则比较元素少1, 继续比较, 最终所有值的位置都确定.

冒泡排序, 共n-1趟(i的次数)排序, , 每趟比较n次(j的次数),  即n+(n-1)+...+3+2 = n(n-1)/2;

时间复杂度为O(n^2);

代码:

/*
* InsertionSort.cpp
*
*  Created on: 2014.4.23
*      Author: Spike
*/

/*eclipse cdt, gcc 4.8.1*/

#include <iostream>
#include <vector>

using namespace std;

void print(const std::vector<int>& L) {
for (auto i : L) {
std::cout << i << " ";
}
std::cout << std::endl;
}

void BubbleSort(std::vector<int>& L) {
std::size_t len = L.size();
int temp;
for (std::size_t i=0; i<len-1; ++i) {
for (std::size_t j=0; j < len-i-1; ++j) {
if (L[j+1] < L[j]) {
temp = L[j];
L[j] = L[j+1];
L[j+1] = temp;
}
}
print(L);
}
}

int main(void) {
std::vector<int> L = {49, 38, 65, 97, 76, 13, 27, 49, 55, 4};
BubbleSort(L);
std::cout << "result : "; print(L);

}

输出:

38 49 65 76 13 27 49 55 4 97
38 49 65 13 27 49 55 4 76 97
38 49 13 27 49 55 4 65 76 97
38 13 27 49 49 4 55 65 76 97
13 27 38 49 4 49 55 65 76 97
13 27 38 4 49 49 55 65 76 97
13 27 4 38 49 49 55 65 76 97
13 4 27 38 49 49 55 65 76 97
4 13 27 38 49 49 55 65 76 97
result : 4 13 27 38 49 49 55 65 76 97


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