Bubble sort why the best responsible degree is O (n)

Source: Internet
Author: User

Bubble sort why the best responsible degree is O (n)

As the saying goes, martial arts is high-strength or not is a person's internal skills, the duel between the real masters, are the internal organs! Programmers are the same, in order to advance, must be from the basis of the crawl, the algorithm is the most important, so recently in the study of algorithms, first from the sorting practice.

Often see the book, the blog said bubble sort the best complexity of O (n), but I look at the code has been counted O (n^2), the code is as follows:

    

Later, after some research, I found that the bubble sort I wrote is just a basic demo, the complexity is always O (n^2), and then after some optimization, found that the best complexity can reach O (n), the code is as follows:

    

When the passed in array is a positive sequence, it executes

This way, the first layer loop executes only 1 times, so the complexity is O (N).

Make a record here, hoping to help the classmates who have doubts.

,

Bubble sort why the best responsible degree is O (n)

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.