冒泡排序的多种实现

    冒泡排序的思想,是不停的交换,有2层循环,第一层循环说明的是比较的次数,第二层循环是比较的趟数。

    1 是用数组实现(C):

#include<iostream.h>

void main()
{

  int array[] = {45,56,76,234,1,34,23,2,3};
 int temp;
 for(int i=0;i<8;i++)
 {
  for(int j=0;j<8-i;j++)
  {
   if(array[j]>array[j+1])
   {
    temp = array[j]; 
    array[j] = array[j+1];
    array[j+1] = temp;
   }
  }
}

 for(int k=0;k<9;k++)
 {
  cout<<array[k];
  cout<<",";
 }

}

2 用指针实现通用:可以重复使用到数据类型一样的数组排序中

#include<iostream.h>

void sort(int* in, int count);
int main()
{
 int array[] = {45,56,76,234,1,34,23,2,3};
 sort(array,8);
 for(int k=0;k<9;k++)
 {
  cout<<array[k];
  cout<<",";
 }
 return 0;
}

void sort(int* in, int count)
{
 int x;
 int y;
 int temp;
 for(y=0;y<count-1;y++)
 {
  for(x=1;x<count-y;x++)
  {
   if((*(in+x))>(*(in+x-1)))
   {
    temp=(*(in+x-1));
    (*(in+x-1))=(*(in+x));
    (*(in+x))=temp;
   }
  }
 }
}

  3 是用C++模版实现 好处是用一个函数实现多个数据类型的排序。这就是范型的特点。

#include "iostream.h"

template<class T>

class doit
{
    private:
    int x,y;
    T temp;
    public:
    doit(T* in,int count)
 {
     for(y=0;y<count-1;y++)
  {
   for(x=1;x<count-y;x++)
   {
    if((*(in+x))>(*(in+x-1)))
    {
     temp=(*(in+x-1));
        (*(in+x-1))=(*(in+x));
        (*(in+x))=temp;
    }
   }
  }
 }
};

int main()
{
 double a[4]={1.1,1.3,1.9,2.2};
 doit<double> d(a,4);
 for(int i=0;i<4;i++)
 {
  cout<<a[i]<<endl;
 }
 return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值