Bubble sort and bubble sort
Recently, I have been interviewing new students for a few simple interview questions. The Bubble sorting method is one of them. Many people think that the bubble is simple and thus neglected. I searched the internet and found many incorrect statements. I wrote it by myself. It's a review.
The C ++ code is as follows:
# Include "stdafx. h "/************************************* ********************************** // Bubble Sorting *//************************************* * *********************************/void BubbleSort (int data [], int n) {for (int I = 0; I <n-1; I ++) {bool exchange = false; for (int j = 0; j <n-i-1; j ++) {if (data [j]> data [j + 1]) {int tmp = data [j]; data [j] = data [j + 1]; data [j + 1] = tmp; exchange = true ;}} if (! Exchange) break;} int _ tmain (int argc, _ TCHAR * argv []) {int data [10] = {-100, 79,-3, 0, 49, 21, 8,200,123 41, 0}; BubbleSort (data, 10); return 0 ;}
Note two problems:
1. the Bubble sorting method compares two adjacent elements, rather than the header elements and the subsequent elements. Some of the online statements are incorrect. In the final analysis, the algorithm does not actually perform the Bubble Sorting by hand, take it for granted;
2. Pay attention to the condition of loop end. It is not necessary to compare until the program ends, but the program can be terminated when there is no exchange operation in the comparison process.