C + + bubble sort algorithm instance _c language

Source: Internet
Author: User

Bubble sort

University study data structure and algorithm at the very beginning, it tells the bubble sort; Bubble sort is a very simple sort algorithm that repeatedly visits the sequence to be sorted, compares two numbers at a time, and exchanges two numbers of comparisons in ascending or descending order. For example, now I want to sort the following data:

10 3 8 0 6 9 2

When you use bubble sort for ascending sorting, the steps for sorting are as follows:

3 10 8 0 6 9 2//10 and 3 for comparison, 10>3, swap position

3 8 10 0 6 9 2//10 compare with 8, 10>8, swap position

3 8 0 10 6 9 2//10 compare with 0, 10>0, swap position

......

3 8 0 6 9 2 10//This time, 10 reached the rightmost, is the largest number, at this time, we start from the beginning of the comparison

3 8 0 6 9 2 10//3 less than 8, so no swap position

3 0 8 6 9 2 10//8 greater than 0, so swap position

......

0 2 3 6 8 9 10

Very simple, that is, let the large number sink below, the decimal slowly floating up. The time complexity of the bubble sort is also O (n^2).

Code implementation

Copy Code code as follows:

#include <iostream>
using namespace Std;

void Bubblesort (int arr[], int length)
{
int temp;
for (int i = 0; i < length; ++i)
{
for (int j = 0; J < length-i-1; ++j)
{
if (Arr[j] > arr[j + 1])
{
temp = Arr[j];
ARR[J] = arr[j + 1];
Arr[j + 1] = temp;
}
}
}
}

int main ()
{
int arr[10] = {2, 4, 1, 0, 8, 4, 8, 9, 20, 7};

Bubblesort (arr, sizeof (arr)/sizeof (arr[0));

for (int i = 0; i < sizeof (arr)/sizeof (arr[0)); ++i)
{
cout<<arr[i]<< "";
}
cout<<endl;

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.