#include<stdio.h>标签:arr,temp,int,bubble,冒泡排序,++,优化,size From: https://blog.51cto.com/u_13606048/6096512
//还可以优化
void bubble_sort(int arr[], int size) {
for (int i = 0; i < size-1; i++) { //共有size-1趟冒泡排序
for (int j = 0; j < size-1-i; j++)
{
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
//优化后
void bubble_sort1(int arr[], int size) {
for (int i = 0; i < size - 1; i++) {
int flag = 1;
for (int j = 0; j < size - 1 - i; j++)
{
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
flag = 0;
}
}
if (flag == 1) {
break;
}
}
}
int main() {
int arr[] = { 9,8,7,6,4,5,2,1,3 };
int arr1[] = { 9,8,7,6,4,5,2,1,3 };
int size = sizeof(arr) / sizeof(arr[0]);
bubble_sort(arr,size);
for (int i = 0; i < size; i++) {
printf("%d", arr[i]);
}
printf("\n");
bubble_sort1(arr1, size);
for (int i = 0; i < size; i++) {
printf("%d", arr1[i]);
}
return 0;
}