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

一.算法描述

冒泡排序算法的运作如下:
    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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值