冒泡排序
冒泡排序(Bubble Sort)是一种交换排序。基本思想是:每次(外循环)遍历序列都把最大(小)的元素放在最前面(通过内循环的“比较-交换”),然后再对剩下的序列重复这个过程,每次遍历之后待排序序列就少一个元素,直到排序完毕。因此,时间复杂度在最坏的情况下是O(N ^ 2)。
算法实现及测试:
#include <iostream> using namespace std; // 冒泡排序 void BubbleSort(int data[], int count) { int auxiliary = 0; bool swap_flag = true; for (int i = 0; i < count && swap_flag; ++i) { swap_flag = false; for (int j = count - 1; j > i; --j) { if (data[j] < data[j - 1]) { auxiliary = data[j - 1]; data[j - 1] = data[j]; data[j] = auxiliary; swap_flag = true; } } } } int main() { int array[] = {9, 6, 3, 8, 7, 1, 5, 2, 4}; BubbleSort(array, 9); for(int i = 0; i < 9; ++i) cout << array[i] << endl; return 0; }
【学习资料】 《大话数据结构》