zoukankan      html  css  js  c++  java
  • 简单的冒泡排序

    冒泡排序是当时学数据结构排序时学的第一个算法,这个冒泡,当时我还挺不理解的,这个跟冒泡有啥关系。

    然后我之后查了百度,如下:

      重复地走访过要排序的数列,一次比较两个元素,如果他们的顺序错误就把他们交换过来。走访数列的工作是重复地进行直到没有再需要交换,也就是说该数列已经排序完成。
    这个算法的名字由来是因为越大的元素会经由交换慢慢“浮”到数列的顶端,故名。
    这个解释很易懂了,之前的数据结构老师讲究手工过程,下面就来个冒泡排序的手工过程。
    待排序数组:
      95,45,15,78,84,51,24,12

    c代码:

    void bubble_sort(int a[], int n);
     
    void bubble_sort(int a[], int n)
    {
        int i, j, temp;
        for (j = 0; j < n - 1; j++)
            for (i = 0; i < n - 1 - j; i++)
            {
                if(a[i] > a[i + 1])
                {
                    temp = a[i];
                    a[i] = a[i + 1];
                    a[i + 1] = temp;
                }
            }
    }
     
    int main()
    {
        int number[SIZE] = {95, 45, 15, 78, 84, 51, 24, 12};
        int i;
        bubble_sort(number, SIZE);
        for (i = 0; i < SIZE; i++)
        {
            printf("%d", number[i]);
        }
        printf("
    ");
    }

    Java代码:

    public class BubbleSort
    {
        public void sort(int[] a)
        {
            int temp = 0;
            for (int i = a.length - 1; i > 0; --i)
            {
                for (int j = 0; j < i; ++j)
                {
                    if (a[j + 1] < a[j])
                    {
                        temp = a[j];
                        a[j] = a[j + 1];
                        a[j + 1] = temp;
                    }
                }
            }
        }
    }

    python版代码:

    def bubbleSort(x):
        xLen = len(x)
        for i in xrange(xLen-1):
            for j in xrange(xLen -1-i):
                if x[j] > x[j+1]:
                    t = x[j]
                    x[j] = x[j+1]
                    x[j+1] = t
        return x
    if __name__ == '__main__'
    #bubbleSort dispaly
    print bubbleSort([95,45,15,78,84,51,24,12])

     

  • 相关阅读:
    scala的Class
    scala的Map
    log4j配置文件详细解释
    学习线程1之建立线程,并启动
    Spring中WebApplicationContext的研究
    Log4j 配置 的webAppRootKey参数问题
    JNDI绑定数据库
    Struts2配置之Struts.properties
    Java多线程-工具篇-BlockingQueue
    StringUtils判断字符串是否为空的方法
  • 原文地址:https://www.cnblogs.com/darcy-hui/p/10782657.html
Copyright © 2011-2022 走看看