Algorithm Review: Bubble Sorting

Source: Internet
Author: User

Thought: for a list, each number is a "bubble". A larger number indicates "heavier". The heaviest bubble moves to the last position of the list, after the bubble is sorted, "Bubbles" are moved to the corresponding positions in the list based on their weights.

 

Algorithm: searches the entire list and compares adjacent elements. If the relative order of the two is incorrect, they are exchanged. The result is that the maximum value "the same as the bubble" is moved to the last position of the list, this is also the proper position in the final sorting list. Search for the list again, move the second largest value to the second last position, and repeat the process until all elements are moved to the correct position.

The following animation demonstrates the entire process of Bubble Sorting for {3, 6, 5, 9, 7, 1, 8, 2, 4:

 

Code implementation [run successfully on VC 2005 ]:

#include "stdafx.h"int main(){        int list[9] ={3,6,5,9,7,1,8,2,4};            int length = sizeof(list)/sizeof(int);            int temp = 0;            for(int i=1;i<length;i++){               bool exchange=false;               for(int j=0;j<length-i;j++){                               if(list[j]>list[j+1]){                               temp= list[j];                               list[j]=list[j+1];                               list[j+1]=temp;                               exchange=true;                        }                                             }                     if(!exchange){                        break;                  }      }            for(int i=0;i<length;i++){             printf("%d\t",list[i]);        }          return 0;}

Exchange is used here. If there is no exchange in a sort, that is, exchange = false, the data is already in order, therefore, you can exit the sorting process.

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.