zoukankan      html  css  js  c++  java
  • 冒泡算法

    一、冒泡算法

    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




  • 相关阅读:
    if语法案例
    其他6-break,continue,exit,return区别
    其他5-6种产生随机数的方法
    其他4-shell脚本后台运行知识
    算法练习 第三周
    回顾MySQL基础
    jsp中使用jQuery获取窗口高度不正确的问题
    初学java 学生管理系统——v04版本 改用web
    web项目中跳转路径的使用
    tomcat部署项目的方式
  • 原文地址:https://www.cnblogs.com/xinyuyuanm/p/3072015.html
Copyright © 2011-2022 走看看