Bubble Sort (Bubble Sort C ++)

Source: Internet
Author: User

"Bubble Sort" is a simple way to sort elements. this sort employs a "bubbling strategy" to get the largetest element to the right. in a bubbling pass, pairs of adjacent elements are compared, the elements are swapped in case the one on the left is greater than the one on the right. at the end of the bubbling pass, we are assured that the largest element is in the right-most position. [cpp] // Bubble. cpp: Defines the entry point for the console application. // # include "stdafx. h "# include <iostream> using namespace std; template <class T> // one bubbling pass bool Bubble (T a [], int n, int & flag) {bool swapped = false; for (int I = 0; I <n-1; I ++) {if (a [I]> a [I + 1]) {swap (a [I], a [I + 1]); swapped = true; flag = I + 1 ;}} return swapped ;} template <class T> void BubbleSort (T a [], int n) {int flag = n; for (int I = flag; I> 1 & Bubble (a, I, flag); I --);} template <class T> void PrintfNum (T a [], int n); int main (int argc, char * argv []) {int a [14] = {9, 3, 7, 1, 4, 5, 8, 10, 11, 12, 13, 14, 15, 16}; cout <"Before sort:" <endl; int flag; printfNum (a, 14); cout <"First Bubble:" <endl; Bubble (a, 14, flag); PrintfNum (a, 14 ); cout <"flag:" <flag <endl; cout <"Bubble Sort:" <endl; BubbleSort (a, 14); PrintfNum (a, 14 ); return 0;} template <class T> void PrintfNum (T a [], int n) {for (int I = 0; I <n; I ++) {cout <a [I] <"," ;}cout <endl ;}

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.