一般冒泡排序和双向冒泡排序

来源:互联网 发布:淘宝佰腾qq申诉 编辑:程序博客网 时间:2024/04/30 04:42

//冒泡排序,大的往上浮,时间复杂度o(n)
void Buble(int a[],int N)
{
   for(int i=0;i<N-1;i++)
      for(int j=0;j < N-i-1;j++)
      {
        if(a[j]>a[j+1])
        {
           int t = a[j];
           a[j] = a[j+1];
           a[j+1] = t;
        }
      }
}

 

//双向冒泡,冒泡排序升级版

void Bubble_Sort2(int a[ ],int n)
{
  int low=0,high=n-1;
  bool change=true;
  int i,temp;
  while(low<high&&change)
  {
    change=false;
    for(i=low;i<high;i++)
      if(a[i]>a[i+1])
      {
        /* a[i]<->a[i+1];*/
        temp=a[i];
        a[i]=a[i+1];
        a[i+1]=temp;
        change=true;
      }
      high--;

      for(i=high;i>low;i--)
      if(a[i]<a[i-1])
      {
        /* a[i]<->a[i-1]; */
        temp=a[i];
        a[i]=a[i-1];
        a[i-1]=temp;
        change=true;
      }
      low++;
  }//while
}

原创粉丝点击