The bubble sort and its optimization (Java implementation) for getting started with sorting algorithms

Source: Internet
Author: User

Bubble sort idea (small to large):

Compares adjacent two elements, exchanging their positions if the first element is larger than the second element. First, starting with the first element, the first element is compared to the second element, and if the first element is larger than the second element, the position is swapped; next, the second, third element, the big one, and so on, until the last two. At the end of the first comparison, the largest element is placed in the last position. Next, proceed to the second order, from the first element to the penultimate element (because the last one is already the largest), perform the above steps. Proceed in turn.

The optimal worst-case average time complexity at this point is O (n^2).

Optimization: Adds a flag bit, when swapping elements is true, no interchange is false, sort ends.

At this time, the optimal time complexity of the optimization algorithm is O (n), the worst and the average is O (n^2).

The bubble sort and its optimization (Java implementation) for getting started with sorting algorithms

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.