冒泡排序
#include <iostream>
using namespace std;
void bubbleSort(int arr[], int n) {
bool flag = false;
for (int i = 0; i < n-1; i++) { // 外层循环,控制排序的轮数
for (int j = 0; j < n-i-1 ; j++) { // 内层循环,控制每轮比较的次数
if (arr[j] > arr[j + 1]) { // 如果前一个元素比后一个元素大
// 交换两个元素的位置
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
flag = true;
}
}
}
if(flag==false)
{
return;
}
}
int main() {
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(arr) / sizeof(arr[0]);
cout << "Ori array: \n";
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
cout << endl;
bubbleSort(arr, n);
cout << "Sorted array: \n";
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
cout << endl;
return 0;
}
标签:arr,false,int,冒泡排序,flag,sizeof
From: https://www.cnblogs.com/lwp-nicol/p/18288291