Bubble sort of sorting algorithm

Source: Internet
Author: User

Basic idea:

The bubble sort is implemented by exchanging two elements, the idea being:

The first trip will be sorted sequence (a[0]~a[n-1]) from the go, 22 adjacent elements to compare, if the latter small, then exchange, compare n-1 times;

At the end of the first trip, the largest element is exchanged to a[n-1] (i.e. sink), and the next order only needs to be done in (a[0]~a[n-2]);

If the element is not swapped in a certain order, the sub-sequence is ordered, then the next order is not made. This method is used for up to n-1 trips.


Bubble Sort Example:


Code:

void Bubblesort (int a[],int n)//bubble Sort {int I, J, Last;i=n-1;while (i>0) {last=0;//up to n-1 trip for (j=0; j<i; j + +)//compare from Go {if (a[j+1]<a[j])//The previous one is larger, swap {swap (a[j],a[j+1]);    Last=j;}} i=last;//If there is no interchange element in the order, then last is 0,i 0 jumps out of the loop}}


Improved bubbling algorithm:

The ordering of the maximum and minimum values for forward and reverse. (PS: In fact, some authors will think of the above algorithm as a bubbling Improvement algorithm ~ ~)

void Improvebubblesort (int a[],int N)//improved bubbling {int Low,high,j;low=0;high=n-1;while (Low

time complexity Analysis:

Bubble sort is best done in a single trip, n-1 times, so the best case time complexity is O (n), without moving the element, the worst case of n-1 trip, the first I trip compared n-i times, the worst case time complexity is O (n^2).

In addition, the bubbling sort is a stable sorting method after the bubble has been sequenced to finalize the final position of the element.


Resources:

"Data structure" Chen Huinan People's post and telecommunications press

Bubble sort of 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.