This example for you to share the C + + bubble sort specific code, for your reference, the specific content is as follows
1、 Thinking:
Bubble sort algorithm principle:
1. Compare the adjacent elements. If the first number is larger than the second number, exchange them.
2. Do the same work for each pair of adjacent elements, from the first pair at the beginning to the last pair at the end. At this point, the last element should be the largest number.
3. Repeat the above steps for all elements except the last one. (because the last one has been arranged, which is the largest number)
4. Continue to repeat the above steps for fewer and fewer elements each time until there is no pair of numbers to compare. (followed by the second largest number and continued)
For example: using bubble sort: 25 16 9 90 23
The first round: if a number is greater than the following number, then exchange;
The first time: 16 25 9 90 23
The second time: 16 9 25 90 23
…..
In the end: 16 9 25 23 90 the biggest number came to the end.
Comparison times: 4 times
Second round: get the second largest number: 9 16 23 25 90
At this point, the order has been arranged, and you can end the sorting ahead of time.
2、 Implementation code:
#include <iostream>
using namespace std;
const int maxSize = 20;
//Bubble sort: sort from small to large
template <class T>
void BubbleSort(T arr[], int n) {
int i, j, flag;
T temp;
For (I = 0; I < n-1; I + +) {// for n-1 times
Flag = 0; // exchange flag, 0 means no exchange, 1 means exchange
For (J = 0; J < (n-i-1); j + +) {// the maximum subscript of the array is n-1
If (arr [J] > arr [J + 1]) {// reverse order is exchanged
Flag = 1; // with swap
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
If (flag = = 0) // there is no exchange, indicating that all of them are in order and end ahead of time
break;
} // for
} // BubbleSort
int main(int argc, const char * argv[]) {
int i, n, arr[maxSize];
Cout < "please enter the number of numbers to sort":;
cin >> n;
Cout < "please enter the number to sort":;
for(i = 0; i < n; i++)
cin >> arr[i];
Cout < before sorting: < endl;
for(i = 0; i < n; i++)
cout << arr[i] << " ";
cout << endl;
BubbleSort(arr, n);
Cout < after sorting: < endl;
for(i = 0; i < n; i++)
cout << arr[i] << " ";
cout << endl;
return 0;
}
Test results:
The above is the whole content of this article, I hope to help you learn, and I hope you can support developer more.