Bubble sort Bubble_Sort

The basic principle : to bubble sort, the basic idea is to start with the first element, and an array of data behind it successively comparing neighboring data, i.e., 1 and 2 compare, compare 2 and 3, a and a + comparison 1, and comparison second until the countdown of the first, if the order can not be exchanged, such a maximum down element will be placed at the last position [in ascending order as an example, this is understood bubble sort focus. Next, during the time this sort, but on the penultimate deadline. Finally it got left element elements first position and the second position are compared. This should be relatively easy to understand, not on the map it. But if there is enough time, I was willing to put up on the map.

Time complexity: obviously O (n ^ 2)

Code:

 

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

    public static void main(String []args)
    {
        int [] a = {3, 2, 5, 1, 8, 1, 11, 8};
        bubble(a);
        for (int i : a)
            System.out.print(i+" ");
    }

 

 

 

Guess you like

Origin www.cnblogs.com/lbrs/p/11886536.html