算法学习之排序(2)--冒泡排序

来源:互联网 发布:编程之魂 编辑:程序博客网 时间:2024/05/21 16:22

一.算法描述

冒泡排序算法的运作如下:
    1. 比较相邻的元素。如果第一个比第二个大,就交换他们两个。
    2. 对每一对相邻元素作同样的工作,从开始第一对到结尾的最后一对。这步做完后,最后的元素会是最大的数。
    3. 针对所有的元素重复以上的步骤,除了最后一个。
    4. 持续每次对越来越少的元素重复上面的步骤,直到没有任何一对数字需要比较。


二.时间复杂度

1.最好情况:对于已经排序好的数组,冒泡法需要的比较次数为(n-1)+(n-2)+...+1=n(n-1)/2,交换次数为0,因此,最好情况下,冒泡排序的时间复杂度为O(n^2).
2.最差情况:对于逆序的数组,冒泡法需要的比较次数为(n-1)+(n-2)+...+1=n(n-1)/2,交换次数为(n-1)+(n-2)+...+1=n(n-1)/2,因此,最差情况下,冒泡法的时间复杂度为O(n^2).
3.平均情况:在平均情况下的时间代价是最差情况下的一半,因此,平均情况下,插入排序的时间复杂度也为O(n^2).


三.空间复杂度

冒泡排序是in-place排序,空间复杂度为O(1)


四.C++实现

#include <iostream>#include "Sort.h"bool BubbleSort(std::vector<int>& Array){    // return false if the array is empty.    if (Array.empty())    {        std::cout << "The size of the Array is empty." << std::endl;        return false;    }    // return the origin array if there are only one element of the array    if (Array.size() == 1)    {        std::cout << "The size of the array is one." << std::endl;        return true;    }    // bubble sort    int Size = Array.size();    for (int OuterIndex = 0; OuterIndex < Size; OuterIndex++)    {        for (int InnerIndex = 0; InnerIndex < (Size - OuterIndex - 1); InnerIndex++)        {            int Now = Array[InnerIndex];            int Next = Array[InnerIndex + 1];            // exchange the value if the Now is bigger than Next            if (Now > Next)            {                Array[InnerIndex + 1] = Now;                Array[InnerIndex] = Next;            }        }    }    return true;}



五.参考文献

[1] Shaffer C A. Practical Introduction to Data Structure and Algorithm Analysis (C++ Edition)[J]. 2002.
[2] 科曼 and 金贵, 算法导论: 机械工业出版社, 2006.
[3] T. H. Cormen, C. E. Leiserson, R. L. Rivest, and C. Stein, "算法导论 (影印版)," ed: 北京: 高等教育出版社.
[4]http://zh.wikipedia.org/wiki/%E5%86%92%E6%B3%A1%E6%8E%92%E5%BA%8F


版权所有,欢迎转载,转载请注明出处,谢谢微笑
0 0