冒泡排序

//  Bubble.cpp : Defines the entry point for the console application.
//
// 冒泡排序是对相临元素进行比较,如果左边的元素大于右边则交换,
//   这样一直持续下去。

#include 
" stdafx.h "
#include 
< iostream >
#include 
< algorithm >
using   namespace  std;

// 第一种方法
template  < class  T >
void  Bubble(T a[],  int  n)
{
    
for(int i = 0; i < n-1; i++)//注意是n-1
        if(a[i] > a[i+1])swap(a[i], a[i+1]);
}


template
< class  T >
void  BubbleSort(T a[],  int  n)
{
    
for(int i = n; i >1; i--)
        Bubble(a, i);
}

// 第二种方法,改进方法。

// 冒泡排序的改进版:如果在一次冒泡的过程中没有发生元素交换,
// 说明数组已经按序排列,没必要进行冒泡排序。
template < class  T >
bool  Bubble(T a[],  int  n)
{
    
bool swapped = false;
    
for(int i = 0; i < n-1; i++)
        
if(a[i] > a[i+1])
            swap(a[i], a[i
+1]);
        swapped 
= true;//发生了交换
        return swapped;
}

template 
< class   T >
void  BubbleSort(T a[],  int  n)
{
    
for(int i = n; i > 1&& Bubble(a,i); i--);
}


int  main( int  argc,  char *  argv[])
{   

    
int a[] = {4,7,8,99,2,4,85,1,47,26};
    
const int icon = sizeof(a)/ sizeof(&a[0]);
    BubbleSort(a,icon);
    
for(int i = 0; i < icon; i++)
        cout
<<a[i]<<endl;

    
return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

yshuise

权术横行

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值