An improved sorting algorithm

Source: Internet
Author: User

Before writing to several sort of algorithms, for example:

//Bubble SortvoidBubblesort (unsignedChar*list,intlength) {    inti,j,temp;  for(i =0; i < length; i++)    {         for(j =0; J < Length-i-1; J + +)        {            if(list[j+1] <List[j]) {Temp= List[j +1]; List[j+1] =List[j]; LIST[J]=temp; }        }    }}

The original operation is the exchange of data, the algorithm Time review degree is O (n^2).

But if we need to sort the data such as: (1 2 3 5 6 9) or simply swap a few times to sort well such as (2 1 3 5 6 9), the loop behind the algorithm is not working hard at all.

At this point we just need to add a flag to avoid the situation.

//Bubble SortvoidBubblesort (unsignedChar*list,intlength) {    inti,j,temp; intFlag;  for(i =0, flag =1; I < length && flag; i++) {flag=0;  for(j =0; J < Length-i-1; J + +)        {            if(list[j+1] <List[j]) {Temp= List[j +1]; List[j+1] =List[j]; LIST[J]=temp; Flag=1; }        }    }}

When the sequence itself is correct, in the best case: The time Review degree is O (n).

Related: Views on data and structure

An improved sorting algorithm

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.