交换排序之冒泡排序优化源码及时间复杂度

常见的交换排序包括冒泡排序和快速排序。

用于显示的代码:show.cpp

#include <iostream>

using namespace std;

template <class T>

void showww(T* t, int n)
{
    for(int i=0; i<n; i++)
      cout << *(t+i) << endl;
}

冒泡排序

bubble.cpp

template <class T>

int bubble_sort(T* t, int n)
{
    int camp_times = 0;
    for(int j=0; j<n-1; j++)
    {
        for(int k=j+1; k<n; k++)
        {
            camp_times++;
            if(t[j] > t[k])
            {
                T tmp = t[j];
                t[j] = t[k];
                t[k] = tmp;
            }
        }
    }
    return camp_times;
}

主函数:

#include "bubble.cpp"
#include "show.cpp"

int main()
{
    double num[] = {1.2, 4.55, 2.34, 56.56, 78.3, -23.5, 9.8};
    int numi[] = {1, 2, 3, 4, 5, 6, 7};
    int n = 7;
    cout << "--------------before--------------\n";
    showww(num, n);
    int campare_times = bubble_sort(num,n);
    cout << "--------------after--------------\n";
    showww(num,n);
    cout << "---------compare_times: " << campare_times << "---------\n" << endl;
    cout << "--------------before--------------\n";
    showww(numi, n);
    campare_times = bubble_sort(numi,n);
    cout << "--------------after--------------\n";
    showww(numi,n);
    cout << "---------compare_times: " << campare_times << "---------" << endl;
    return 0;
}

执行结果:
这里写图片描述

时间复杂度

o(n2)

空间复杂度

o(1)

空间复杂度不受问题规模影响,为就地排序。

优化后的冒泡排序

优化原理:当某一次排序不再发生冒泡(大小交换)时,说明已经有序了,则不再进行下一轮排序。
最好的情况下(排序前就已经有序),时间复杂度为:

o(n)

bubble_sort.cpp

template <class T>

int bubble_sort(T* t, int n)
{
    int camp_times = 0;
    bool exchange = false;
    for(int j=0; j<n-1; j++)
    {
        for(int k=j+1; k<n; k++)
        {
            camp_times++;
            if(t[j] > t[k])
            {
                T tmp = t[j];
                t[j] = t[k];
                t[k] = tmp;
            exchange = true;
            }
        }
        if(!exchange)
          break;
    }
    return camp_times;
}

执行结果:
这里写图片描述

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值