#include #define Max 5 int main(int argc, const char * argv[]) { int a[Max] = {22,16,80,1,10}; int time = 0; int count = 0; for (int i = 0; i < Max - 1 ; i++) { for (int j = 0; j < (Max - 1 - i); j++) { time++; if (a[j] > a[j+1] ) { int tmp; tmp = a[j]; a[j] = a[j+1]; a[j+1] = tmp; count++; } } } printf("交换次数%d\n",count); printf("执行次数%d\n",time); //遍历 for (int i = 0 ; i < Max; i++) { printf("%d ",a[i]); } return 0; } Question : 1.我这已经是最优的了吧 2.第二个for循环的j条件,为什么要设置成 Max - i - 1 ,Max表示数组长度.
For question 2, every time you sort, the largest number will definitely be placed at the end, so during the second comparison, there is no need to operate on the last number
No
It is already sorted from
Max - 1- i
到Max - 1
objectiv-c
What the hellQuestion 1: There is another point that can be optimized in this algorithm, which is the processing of already ordered sequences, such as {1, 2, 3, 5, 4};. The processing method is to jump out of the loop if there is no exchange. However, I have not completed the optimization. , because the sorting could not be completed after testing.
Question 2: The setting of j condition: depends on the value of i, because i has been sorted before, and the last element of the array has also been sorted.