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;
}