A compulsory course for beginners and advanced programmers the use of bubble sort

Let’s focus on bubble sorting, which is the most basic sorting algorithm, and it is also very practical. !

Bubble Sort is also a simple and intuitive sorting algorithm. It repeatedly walks through the sequence to be sorted, comparing two elements at a time, and swapping them if they are in the wrong order. The work of visiting the sequence is repeated until no more exchanges are needed, that is, the sequence has been sorted. The name of this algorithm comes from the fact that the smaller elements are slowly “floated” to the top of the sequence by swapping.

As one of the simplest sorting algorithms, bubble sort gives me the same feeling that Abandon appears in a word book, every time it is first on the first page, so it is the most familiar. There is also an optimization algorithm for bubble sort, which is to set up a flag. When the elements are not exchanged during a sequence traversal, it is proved that the sequence is already in order. But this improvement doesn’t do much to improve performance.

1. Algorithm steps

1) Compare adjacent elements. If the first is bigger than the second, swap the two of them.

2) Do the same for each pair of adjacent elements, from the first pair at the beginning to the last pair at the end. After this step, the last element will be the largest number.

3) Repeat the above steps for all elements except the last one.

4) Continue to repeat the above steps for fewer and fewer elements each time, until there are no pairs of numbers to compare.

2. Code implementation

JavaScript example

function  bubbleSort ( arr ) {
     var len = arr.length;
     for ( var i = 0 ; i < len - 1 ; i++) {
         for ( var j = 0 ; j < len - 1 - i; j++) {
             if (arr [j] > arr[j+ 1 ]) {         // pairwise comparison of adjacent elements 
                var temp = arr[j+ 1 ];         // element exchange 
                arr[j+ 1 ] = arr[j];
                arr[j] = temp;
            }
        }
    }
    return arr;
}

Python instance

def bubbleSort(arr):
    for i in range(1, len(arr)):
        for j in range(0, len(arr)-i):
            if arr[j] > arr[j+1]:
                arr[j], arr[j + 1] = arr[j + 1], arr[j]
    return arr

Go instance

func bubbleSort(arr []int) []int {
        length := len(arr)
        for i := 0; i < length; i++ {
                for j := 0; j < length-1-i; j++ {
                        if arr[j] > arr[j+1] {
                                arr[j], arr[j+1] = arr[j+1], arr[j]
                        }
                }
        }
        return arr
}

Java instance

public class BubbleSort implements IArraySort {

    @Override 
    public  int [] sort( int [] sourceArray) throws Exception {
         // Copy arr without changing the parameter content 
        int [] arr = Arrays.copyOf(sourceArray, sourceArray.length);

        for ( int i = 1 ; i < arr.length; i++) {
             // Set a flag, if it is true, it means that there is no exchange in this loop, that is, the sequence to be sorted has been sorted and the sorting has been completed. 
            boolean flag = true ;

            for (int j = 0; j < arr.length - i; j++) {
                if (arr[j] > arr[j + 1]) {
                    int tmp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = tmp;

                    flag = false ;
                }
            }

            if (flag) {
                break;
            }
        }
        return arr;
    }
}

PHP example

function bubbleSort($arr)
{
    $len = count($arr);
    for ($i = 0; $i < $len - 1; $i++) {
        for ($j = 0; $j < $len - 1 - $i; $j++) {
            if ($arr[$j] > $arr[$j+1]) {
                $tmp = $arr[$j];
                $arr[$j] = $arr[$j+1];
                $arr[$j+1] = $tmp;
            }
        }
    }
    return $arr;
}

C language example

#include <stdio.h>
void bubble_sort(int arr[], int len) {
        int i, j, temp;
        for (i = 0; i < len - 1; i++)
                for (j = 0; j < len - 1 - i; j++)
                        if (arr[j] > arr[j + 1]) {
                                temp = arr[j];
                                arr[j] = arr[j + 1];
                                arr[j + 1] = temp;
                        }
}
int main() {
        int arr[] = { 22, 34, 3, 32, 82, 55, 89, 50, 37, 5, 64, 35, 9, 70 };
        int len = (int) sizeof(arr) / sizeof(*arr);
        bubble_sort(arr, len);
        int i;
        for (i = 0; i < len; i++)
                printf("%d ", arr[i]);
        return 0;
}

C++ example

# include  <iostream>
 using  namespace  std ;
 template < typename T> //Integer or floating point numbers can be used, if you want to use a class or a structure, you must overload the greater than (>) operator 
void  bubble_sort ( Tarr[], int len)  {
         int i, j;
         for (i = 0 ; i < len - 1 ; i++)
                 for (j = 0 ; j < len - 1 - i; j++)
                         if (arr[j] > arr[j + 1 ])
                                swap(arr[j], arr[j + 1]);
}
int main() {
        int arr[] = { 61, 17, 29, 22, 34, 60, 72, 21, 50, 1, 62 };
        int len = (int) sizeof(arr) / sizeof(*arr);
        bubble_sort(arr, len);
        for (int i = 0; i < len; i++)
                cout << arr[i] << ' ';
        cout << endl;
        float arrf[] = { 17.5, 19.1, 0.6, 1.9, 10.5, 12.4, 3.8, 19.7, 1.5, 25.4, 28.6, 4.4, 23.8, 5.4 };
        len = (float) sizeof(arrf) / sizeof(*arrf);
        bubble_sort(arrf, len);
        for (int i = 0; i < len; i++)
                cout << arrf[i] << ' '<<endl;
        return 0;
}

Leave a Comment

Your email address will not be published. Required fields are marked *