冒泡排序排行榜c++
时间: 2024-01-16 17:18:47 浏览: 29
以下是使用C++实现冒泡排序的代码示例:
```cpp
#include <iostream>
using namespace std;
void bubbleSort(int arr[], int n) {
for (int i = 0; i < n-1; i++) {
for (int j = 0; j < n-i-1; j++) {
if (arr[j] > arr[j+1]) {
// 交换arr[j]和arr[j+1]
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
int main() {
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(arr)/sizeof(arr[0]);
bubbleSort(arr, n);
cout << "排序后的数组:";
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
return 0;
}
```
运行上述代码,将会输出排好序的数组:
```
排序后的数组:11 12 22 25 34 64 90
```
相关问题
排行榜冒泡排序c++
以下是使用冒泡排序算法对排行榜进行排序的C++代码示例:
```cpp
#include <iostream>
using namespace std;
void bubbleSort(int arr[], int n) {
for (int i = 0; i < n-1; i++) {
for (int j = 0; j < n-i-1; j++) {
if (arr[j] < arr[j+1]) {
// 交换arr[j]和arr[j+1]
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
int main() {
int scores[] = {90, 85, 95, 80, 70};
int n = sizeof(scores) / sizeof(scores[0]);
cout << "排行榜排序前的分数:";
for (int i = 0; i < n; i++) {
cout << scores[i] << " ";
}
cout << endl;
bubbleSort(scores, n);
cout << "排行榜排序后的分数:";
for (int i = 0; i < n; i++) {
cout << scores[i] << " ";
}
cout << endl;
return 0;
}
```
运行以上代码,将会输出排行榜排序前和排序后的分数。
冒泡排序优化算法c++
冒泡排序是一种简单但效率较低的排序算法,其基本思想是通过相邻元素的比较和交换来将较大的元素逐渐“浮”到数组的末尾。冒泡排序的时间复杂度为O(n^2)。
在冒泡排序的基础上,可以进行一些优化来提高算法的效率。以下是两种常见的冒泡排序优化算法:
1. 设置标志位:在每一轮的比较中,如果没有发生元素交换,则说明数组已经有序,可以提前结束排序。
```cpp
void bubbleSort(int arr[], int n) {
bool flag = true; // 标志位
for (int i = 0; i < n - 1 && flag; ++i) {
flag = false;
for (int j = 0; j < n - i - 1; ++j) {
if (arr[j] > arr[j + 1]) {
swap(arr[j], arr[j + 1]);
flag = true;
}
}
}
}
```
2. 记录最后一次交换位置:在每一轮的比较中,记录最后一次发生元素交换的位置,下一轮比较只需要进行到该位置即可。
```cpp
void bubbleSort(int arr[], int n) {
int lastSwapIndex = n - 1; // 最后一次交换位置
int k;
while (lastSwapIndex > 0) {
k = lastSwapIndex;
lastSwapIndex = 0;
for (int j = 0; j < k; ++j) {
if (arr[j] > arr[j + 1]) {
swap(arr[j], arr[j + 1]);
lastSwapIndex = j;
}
}
}
}
```