优化后的冒泡排序(Bubble Sort)

来源:互联网 发布:海外淘宝网 编辑:程序博客网 时间:2024/06/01 08:11

冒泡排序

时间复杂度(Time Complexity)

假设:数组内有n个元素
外循环:最多执行n-1次
内循环:最多扫描n-1次,交换n-1次;因此共为2(n-1)次
==>
时间复杂度:

T(n)=O[2(n1)2]=O(n2)

空间复杂度(Space Complexity)

空间复杂度:

S(n)=O(1)

算法描述

这里写图片描述

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
原创粉丝点击