1. Sort 10 numbers by bubble

Source: Internet
Author: User
[Principle] It is a simple sorting algorithm. It traverses several secondary sorting columns, and each time it goes through, it will compare the size of two adjacent numbers from the past to the next; if the former is larger than the latter, it will switch their positions. In this way, after a traversal, the maximum element is at the end of the series. In the same way, the second largest element is arranged before the largest element. Repeat this operation until the entire sequence is ordered. [Complexity]

The time complexity of Bubble Sorting is O (n2), and the space complexity is O (n). It is a stable sorting algorithm.

Note that after each bubble round, the last number must be the maximum value after this round of sorting. The next round does not have to be involved in the bubble. So the upper limit of the internal loop is the size-i-1.

 

[Code]

# Include <iostream> using namespace STD; Template <class T> void bubble_sort (T array [], const int size) {T temp; // The intermediate variable int flag; // key code used to mark for (INT m = 0; m <size-1; m ++) // bubble sort, and determine the boundary of the External Loop (that is, the maximum value of the loop) {flag = 0; For (INT n = 0; n <size-1-m; n ++) {If (array [N]> array [n + 1]) // The internal loop is used to compare and exchange data {temp = array [N]; array [N] = array [n + 1]; array [n + 1] = temp; flag = 1; // If switching occurs, set it to 1} If (flag = 0) {break; // if no exchange occurs, the sequence is sorted }}int main () {int temp; // The intermediate variable int A [10]; cout <"Please input 10 numbers:" <Endl; for (INT I = 0; I <10; I ++) // enter the original array {CIN> A [I];} bubble_sort (A, sizeof () /sizeof (INT); For (Int J = 0; j <10; j ++) // output the sorted Array {cout <A [J] <"" ;}return 0 ;}

 

 

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.