冒泡算法

一、冒泡算法

1、方式一

 

[c-sharp]   view plain copy
 
  1. int bubble_sort(int Array[],int Size)
  2. {
  3.     int i,j,temp;

  4.     if(Array == NULL)
  5.         return -1;

  6.     for(i=0;i<Size-1;i++) {  
  7.         for(j=0;j<Size-1-i;j++) {  
  8.             if(Array[j]>Array[j+1]) {  
  9.                 temp = Array[j];  
  10.                 Array[j] = Array[j+1];  
  11.                 Array[j+1] = temp;  
  12.             }  
  13.         }  
  14.     }
  15.     return 0;  
  16. }  

 2、方式二

 

int bubble_sort(int Array[], int size)
{
    int i = size, j;
    int temp;
    if(Array == NULL)
        return -1;
   while(i-- > 0) {
        for(j = 0; j < i - 1; j++) {
            if(Array[j] > Array[j + 1]) {
                temp = Array[j];
                Array[j] = Array[j + 1];
                Array[j + 1] = temp;
            }
        }
    }
    return 0;
}


 3、方式三

 

int bubble_sort(int Array[], int size)
{
    int i = size, j;
    int temp;
    if(Array == NULL)
        return -1;
   for(i = size; i > 0; i--) {
        for(j = 0; j < i - 1; j++) {
            if(Array[j] > Array[j + 1]) {
                temp = Array[j];
                Array[j] = Array[j + 1];
                Array[j + 1] = temp;
            }
        }
    }
    return 0;
}

二、冒泡算法优化

在函数中定义一个bool 的变量 issorted ,在每趟对剩余的数字排序时,先把它设为true,然后当发生两个两个相邻的数没有按要求排时,在交换这两个数的同时,把issorted设为false,不然就一直保持为true。

      在进行好一趟排序之后,测试issorted这个变量的值,如果保持true,就说明已经排好序了,停止继续排序,不然进行下一趟排序。

具体代码:

 

[c-sharp]  view plain copy
 
  1. void bubble_sort(int Array[], int Size)
  2. {  
  3.     int i,j,temp;  
  4.     bool issorted;

  5.     for(i=0; i<Size-1; i++){  
  6.         issorted = true;  
  7.         for(j=0; j<Size-1-i; j++){  
  8.             if(Array[j] > Array[j+1]){  
  9.                 temp = Array[j];  
  10.                 Array[j] = Array[j+1];  
  11.                 Array[j+1] = temp;  
  12.                 issorted = false;  
  13.             }  
  14.         }  
  15.         if(issorted)  
  16.             break;  
  17.     }  
  18. }  

 

参考文章:

冒泡算法优化 http://blog.csdn.net/lengyuhong/article/details/4659552




 

posted @ 2013-05-10 21:18  xinyuyuanm  阅读(311)  评论(0编辑  收藏  举报