C語言:冒泡法排序一組數,如何優化?
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>
int main()
{
int arr[] = { 5, 6, 7, 8, 9 ,1, 2, 3, 4};
int i = 0;
int j = 0;
int flag;
int size = sizeof(arr) / sizeof(arr[0]);
for (i = 0; i < size- 1 ; i++)
{
flag = 1;//設置標志位,優化冒泡
for (j = 0; j < size - 1 - i ; j++)
{
if (arr[j] < arr[j + 1])
{
int tmp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = tmp;
flag = 0;
}
}
if (flag) //說明未進入if內部,即尚未交換已經是所需的輸出順序
break;
}
for (i = 0; i < size; i++)
{
printf("%d ", arr[i]);
}
system("pause");
return 0;
}