zoukankan      html  css  js  c++  java
  • Bubble Sort

    referrence: GeeksforGeeks

    Bubble sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in wrong order.

    Example:
    First Pass:
    5 1 4 2 8 ) –> ( 1 5 4 2 8 ), Here, algorithm compares the first two elements, and swaps since 5 > 1.
    ( 1 5 4 2 8 ) –>  ( 1 4 5 2 8 ), Swap since 5 > 4
    ( 1 4 5 2 8 ) –>  ( 1 4 2 5 8 ), Swap since 5 > 2
    ( 1 4 2 5 8 ) –> ( 1 4 2 5 8 ), Now, since these elements are already in order (8 > 5), algorithm does not swap them.

    After first pass, we put largest bubble at bottom.

    Second Pass:
    1 4 2 5 8 ) –> ( 1 4 2 5 8 )
    ( 1 4 2 5 8 ) –> ( 1 2 4 5 8 ), Swap since 4 > 2
    ( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
    ( 1 2 4 5 8 ) –>  ( 1 2 4 5 8 )
    Now, the array is already sorted, but our algorithm does not know if it is completed. The algorithm needs one whole pass without any swap to know it is sorted.

    After second pass, we put second largest bubble at bottom.

    Third Pass:
    1 2 4 5 8 ) –> ( 1 2 4 5 8 )
    ( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
    ( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
    ( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )

    .....

     1 class Solution {
     2   public static int[] bubbleSort(int[] num) { 
     3     for (c = num.length - 1; c >= 0; c--) {
     4       for (d = 0; d < c; d++) {
     5         if (array[d] > array[d+1])
     6         {
     7           //swap
     8           int swap       = array[d];
     9           array[d]   = array[d+1];
    10           array[d+1] = swap;
    11         }
    12       }
    13       return num;
    14     }
    15 }

    Time complexity O(n^2), space cost O(1), and it's in-place sorting.

  • 相关阅读:
    使用正则表达式验证密码长度
    创建字符串
    洛谷P1605 迷宫 深度搜索 模板!
    洛谷P5534 【XR-3】等差数列 耻辱!!!
    搜索字母a或A
    洛谷P1200 [USACO1.1]你的飞碟在这儿Your Ride Is Here
    19新生赛 质数中的质数
    洛谷P1055 ISBN号码
    洛谷P 1427 小鱼的数字游戏
    洛谷p1047 校门外的树
  • 原文地址:https://www.cnblogs.com/ireneyanglan/p/4856645.html
Copyright © 2011-2022 走看看