C++ 程序:冒泡排序(标准)
原文:https://www.studytonight.com/cpp-programs/cpp-program-for-bubble-sort-standard
大家好!
在本教程中,我们将学习如何用 C++ 编程语言实现标准/未优化的冒泡排序算法。
为了从头开始理解冒泡排序算法,我们强烈建议您首先访问我们的教程,因为我们已经介绍了它的逐步实现,这里:https://www.studytonight.com/data-structures/bubble-sort
代号:
#include <iostream>
#include<vector>
using namespace std;
//Global variable declaration so that the variables can be used/accessed within any of the methods
int n;
//Separate method to print the list provided by the calling method
void printElems(vector < int > list) {
int i;
for (i = 0; i < n; i++)
cout << list[i] << " ";
}
//The Bubble sort logic
void bubbleSort(vector < int > & a) {
int i, j, k, swap;
int len = a.size();
for (int i = len; i > 0; i--) {
//Any number of variables can be used within the loop provided the syntax is correct.
for (j = 0, k = 1; k < i; j++, k++) {
if (a[j] > a[k]) {
swap = a[j];
a[j] = a[k];
a[k] = swap;
}
}
cout << "\n\nThe elements of the list after Pass " << n - i + 1 << " are : ";
printElems(a);
}
}
int main() {
int i, num;
//Declaring the Vector to store the integer elements to be sorted
vector < int > v;
cout << "\n\nWelcome to Studytonight :-)\n\n\n";
cout << " ===== Program to implement the Bubble sort algo using Vectors, in CPP ===== \n\n";
//taking input from the command line (user)
cout << " Enter the number of integers you want to sort : ";
cin >> n;
cout << "\n\n";
for (i = 0; i < n; i++) {
cout << "Enter number" << i + 1 << " : ";
cin >> num;
v.push_back(num);
}
cout << "\n\nThe elements of the list before applying the Bubble sort algorithm are : ";
//Calling the method to print the actual list
printElems(v);
//Calling the bubble sort algorithm
bubbleSort(v);
cout << "\n\nThe elements of the list after applying the Bubble sort algorithm are : ";
//Calling the method to print the sorted list
printElems(v);
cout << "\n\n\n";
return 0;
}
输出 1:
输出 2: 这个场景将向你解释拥有一个优化的冒泡排序算法的必要性,如果列表在两者之间排序,它可以终止程序,而不是一遍又一遍地执行直到结束。
在上面的例子中,列表在第一遍之后被排序,但是我们仍然一遍又一遍地应用逻辑直到最后一遍。这个问题由下面讨论的气泡排序算法的优化版本来处理。
为了更好的理解,你可以参考我们这里的一个教程:https://www.studytonight.com/data-structures/bubble-sort
如有任何疑问,欢迎在下方评论区提问!
继续学习: