------Bubbling method of exchange sorting and its optimization

Source: Internet
Author: User

Study data structure in the university to learn the bubbling method, as a comparison of the classic sorting mode because of its time is more complex as an entry-level algorithm, although the bubbling algorithm in practical applications, but also has a certain amount of research value, here give three kinds of implementation, the first is the original algorithm time complexity of O (n); The second is to join the flag, so that the algorithm in order to sort the data has been ordered before the end of the early; the third, record the small subscript of the last two elements exchanged after each trip and use it as the upper limit of the next sort, so that the algorithm can reduce the number of comparisons directly across the trailing ordered data elements in the data to be sorted

Bubble sort Primitive Algorithm:

#include <iostream>using namespacestd;template<classT>voidBUBBLESORT_0 (T a[],intN) {     for(intI=1; i<n; i++)    {         for(intj=0; j<n-i;j++)        {            if(a[j]>a[j+1]) {swap (a[j], a[j+1]); }        }    }}

After adding the flag bit:

Template <classT>voidBubblesort_1 (T a[],intN) {    intflag=1;  for(intI=1; I<n && Flag; i++) {flag=0;  for(intj=0; j<n-i;j++)        {            if(a[j]>a[j+1]) {swap (a[j], a[j+1]); Flag=1; }        }    }}

Record the smaller subscripts in the last pair of elements exchanged for each trip

Template <classT>voidBubblesort_2 (T a[],intN) {    intI, J; intLastexchangeindex; I=n-1;  while(i>0) {Lastexchangeindex=0;  for(j=0; j<i;j++)        {            if(a[j]>a[j+1]) {swap (a[j], a[j+1]); Lastexchangeindex=J; }} I=Lastexchangeindex; }}

Main function:

intMain () {inta[]={8,6,9,7,5,0,4,1,3,2}; intn=Ten;    Bubblesort_2 (A, N);  for(intI=0; i<n;i++) cout<<A[i]<<" "; cout<<Endl; return 0;}

------Bubbling method of exchange sorting and its optimization

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.