优化后的冒泡排序(Bubble Sort)
来源:互联网 发布:海外淘宝网 编辑:程序博客网 时间:2024/06/01 08:11
冒泡排序
时间复杂度(Time Complexity)
假设:数组内有n个元素
外循环:最多执行n-1次
内循环:最多扫描n-1次,交换n-1次;因此共为2(n-1)次
==>
时间复杂度:
空间复杂度(Space Complexity)
空间复杂度:
算法描述
1 st round:
In the first iteration, we consider the list[0…n - 1]. As you will see after the first iteration, the largest element of the list is moved to the last position, which is position n – 1, in the list.
2 nd round:
In the second iteration, we consider the list[0…n - 2]. After the second iteration, the second largest element in the list is moved to the position n – 2, which is second to the last position in the list.
In the third iteration, we consider the list[0…n - 3], and so on. As you will see, after each iteration, the size of the unsorted portion of the list shrinks.
……
法一:优化的冒泡排序(含调用函数)
//冒泡排序,生成一个7个元素的数组,但是我们只用a[1]到a[6]这六个元素//两层循环,外面那层为while循环,内层为for循环//使用逻辑变量sorted,使外层循环不必蛮力进行n-1轮交换扫描#include <iostream>using namespace std;int main(){void swap(int * d1,int * d2 ); int n=6; int a[7]; cout<<"input 6 numbers"; for (int j=1;j<7;j++) cin>>a[j]; bool sorted=false; while (!sorted)//外层循环:进行每一轮的扫描 { sorted=true; for (int i=1;i<n;i++)//内层循环:进行每一轮内部的交换扫描 { if (a[i]>a[i+1]) { swap(& a[i],& a[i+1]); sorted=false; } } n--; } for (int k=1;k<7;k++) cout<<a[k]; return 0;}void swap(int * d1,int * d2 ) //自定义函数swap(),用于互换两元素位置{ int m= * d1; * d1= * d2; * d2=m;}
法二:优化的冒泡排序法(不含调用函数)
//优化的冒泡排序(无调用函数版)#include <iostream>using namespace std;int main(){ //step 1:数组的建立 int n=6,m; int a[7]; cout<<"input 6 numbers"; for (int j=1;j<7;j++) cin>>a[j]; bool sorted=false; //step 2:核心步骤,实现排序,循环迭代扫描数组 while (!sorted)//外层循环:进行每一轮的扫描 { sorted=true; for (int i=1;i<n;i++)//内层循环:进行每一轮内部的交换扫描 { if (a[i]>a[i+1]) { m=a[i]; a[i]=a[i+1]; a[i+1]=m; sorted=false; }//与选择排序不同的是,冒泡排序是元素交换位置,而选择排序是脚标交换位置 } n--; } //step 3 :打印排序后的数组 for (int k=1;k<7;k++) cout<<a[k]; return 0;}
0 0
- 优化后的冒泡排序(Bubble Sort)
- 冒泡排序(Bubble Sort)
- 冒泡排序(bubble sort)
- 冒泡排序(Bubble Sort)
- 冒泡排序 (Bubble sort)
- 冒泡排序(bubble sort)
- Bubble Sort(冒泡排序)
- 冒泡排序(Bubble sort)
- 冒泡排序(Bubble Sort)
- 冒泡排序(Bubble Sort)
- 冒泡排序(Bubble Sort)
- 冒泡排序(Bubble Sort)
- Bubble-Sort(冒泡排序)
- 冒泡排序(bubble sort)
- 冒泡排序(Bubble Sort)
- Bubble Sort(冒泡排序)
- 冒泡排序(Bubble sort)
- 冒泡排序(bubble sort)
- 0501
- SPP-NET阅读笔记
- python数据分析与挖掘实战-4
- com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
- 学习淘淘商城第四十五课(使用SolrJ查询索引库)
- 优化后的冒泡排序(Bubble Sort)
- 准备做个Ftp自动更新的程序,提前做下准备
- 【AHOI2013】bzoj3238 差异
- java 读取资源文件最详细解读
- 192_IO流_BufferedReader_接收用户键盘输入
- pip install 出现Exception
- 蓝牙会干掉Zigbee吗?
- 第2章 基本程序设计
- URL get传参中文乱码