Algorithm one: Bubbling algorithm

Source: Internet
Author: User

The so-called bubble algorithm is to think of the sort of water blisters, small on top, big in the bottom

The adjacent two elements are compared, if the front is larger than the back, it is exchanged.

If there is a set of data: 3,6,2,1,9

->3,2,1,6,9

->2,1,3,6,9

->1,2,3,6,9

int main () {int a[] = {3,6,2,1,9};for (int i = 0; i < sizeof (a)/4; i++) {for (int j = 0; J < sizeof (a)/4-i-1; j + +) {if (a[j]>a[j + 1]) {int temp = A[j];a[j] = a[j + 1];a[j + 1] = temp;}}} for (int i = 0; i < sizeof (a)/4; i++) {printf ("%d   ", A[i]);} Cin.get ();}

Time complexity: If it is already lined up, the record moves to N-1, the mobile data is 0, the best complexity is O (N), and if the file is reversed (worst) sorted to N-1 times, each

Sorting requires a N-1 comparison and three data exchange. The complexity is O (N2). The spatial complexity of O (1) bubble sort is a stable sort.

Optimization:

You can add a flag bit and set the tag to flase if the data has been exchanged. If the tag is always ture, there is no data exchanged,

int main () {int a[] = {3,6,2,1,9};       bool flage = true;for (int i = 0; i < sizeof (a)/4; i++) {for            (int j = 0; J < sizeof (a)/4-i-1; j + +) { if (A[j]>a[j + 1]) {int temp = A[j];a[j] = a[j + 1];a[j + 1] = temp;                            Flage = false;}}                if (flage) break                    ;} for (int i = 0; i < sizeof (a)/4; i++) {printf ("%d   ", A[i]);} Cin.get ();}

Algorithm one: Bubbling 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.