Bubble sort and bubble sort

Source: Internet
Author: User

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.

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.