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.