Bubble Sort algorithm

Source: Internet
Author: User

Bubble Sort:

The maximum (minimum) number is found by the comparison of each round, and the ascending (descending) order is obtained until the number of rounds of the array length is compared.

Each round of comparisons is a comparison of the numbers traversed by the array with a number after it (except for the ascending (descending) Order of the parts that have been found by previous comparisons), and if the current number is greater than (less than) a number is exchanged, then the array iterates backwards by a number.

C + + programs:

/* Ascending Presentation */

#include <iostream>

using namespace Std;

const int number=8;

int main () {

int arr[number]={0,2,4,1,10,34,3,5};

int i=0,j=0;//used to iterate over an array

Array before output bubble sort

cout<< "The array before ascending is:" <<endl;

for (i=0;i!=number;i++)

cout<<arr[i]<< ""; cout<<endl;

int k;//for storing

The int m=number;//is used to control the number of loops per round

Number of int n=0;//loops

Sort in descending order

for (i=0;i!=number;i++)

{

m--;//is used to remove arrays that have already been arranged, and the first 22 comparison is the array length minus one

for (j=0;j!=m;j++)

{

if (arr[j]>arr[j+1])

{

K=ARR[J+1];

ARR[J+1]=ARR[J];

Arr[j]=k;

}

n++;

}

}

Output sorted after array

cout<< "Array in ascending order:" <<endl;

for (i=0;i!=number;i++) cout<<arr[i]<< "";

cout<<endl;

cout<< "Number of cycles:" <<n<<endl;

return 0;

}

Bubble Sort algorithm

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.