冒泡排序及改进(C++版)
2015-08-12 16:55
399 查看
冒泡排序:相邻两个数比较,根据大小交换位置
C++代码:
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
相关文章推荐
- C++ function、bind以及lamda表达式
- 如何更好的利用《C++ Primer》学习C++?
- C语言中的#define用法总结
- C语言printf()函数详解和安全隐患
- [leetcode-129]Sum Root to Leaf Numbers(c++)
- Introduce to algorithm--------pseudo code to C/C++ code (chapter 16)
- poj2386C语言解题报告
- c/c++ static 对象
- poj2393解题报告c语言
- poj3253解题报告c语言
- 【effective c++读书笔记】【第6章】继承与面向对象设计(2)
- 【effective c++读书笔记】【第6章】继承与面向对象设计(2)
- C++实现位数组
- 大约 C++ 几个方面分析--overload, override, overwrite, rewrite
- C++/CLI托管
- 在 Visual C++ 中以错误的顺序链接 CRT 库和 MFC 库时出现 LNK2005 错误
- LeetCode 213. House Robber II
- c#引用c++ dll类型转换
- C++标准程序库笔记(4)
- [leetcode-125]Valid Palindrome(c++)