Small Fat sheep Algorithm learning-----bubble sort

Source: Internet
Author: User

The bubbling algorithm, as its name implies, is the data arranged in a certain order.

Algorithm ideas:

Suppose there is an array of such

Int[] arr = {5, 9, 3, 1, 2, 6, 7, 4, 8};

According to the algorithm definition, the output we need is

Int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9};

First, get our original array. Determine the size of arr[0] and arr[1] first. If ARR[0]>ARR[1], their location is exchanged. Then compare the sizes of arr[1] and arr[2], and if arr[1]>arr[2], swap their positions. And so on, after iterating through an array, you can put the largest number at the end of the array. At this point this step was performed by Arr. Length-1 times, both 8 times. Then the second round is executed, and the second largest number is moved to the second-to-last position of the array by traversing the comparison array size. You can then arrange the given array in a new order by bubbling the sort.

About the computation of time complexity:

The first round performed m times, the second round carried out m-1 times, which carried out altogether m-rounds.

So the corresponding time complexity is: O ((1+m)/2) *m. When the smaller constants are ignored, the time complexity of the bubble sort is O (m^2)

Enclose the code implemented by C #:

    

        Static int[] arr = {5, 9, 3, 1, 2, 6, 7, 4, 8};        static void Main (string[] args)        {for            (int i = 0; i < arr. Length-2; i++)            {for                (int j = 0; J < arr. Length-1-I; J + +) {                    if (Arr[j] < Arr[j + 1])                    {                        bubbling (J, j + 1);            }}} foreach (Var A in arr)            {                Console.WriteLine (a);            }            Console.read ();        }        static void bubbling (int one, int)        {            int buff = Arr[one];            Arr[one] = Arr[two];            Arr[two] = buff;        }

Small Fat sheep Algorithm learning-----bubble sort

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.