1st day

来源:互联网 发布:迪拜舞蹈大厦的数据 编辑:程序博客网 时间:2024/04/28 22:27

找出最大和第二大的数。

思路1:用冒泡排序将数按从大到小的顺序排列,数组第一个数即为最大,第二个即为第二大。

#include <stdio.h>int main(){int i;int j;int temp;int a[5] = {5, 7, 8 ,9 ,1};for(i = 0; i < 5; i++){for(j = i; j < 5; j++){if(a[i] < a[j]){temp = a[i];a[i] = a[j];a[j] = temp;}}}for(i = 0; i < 5; i++){printf("%d ", a[i]);}printf("\n");
printf("the biggest num is %d\n", a[0]);printf("the second big num is %d\n", a[1]);}
冒泡排序优化后:

#include <stdio.h>int main(){int i;int j;int temp;int cmpCount = 0; int a[5] = {7, 8, 9, 1, 5};for(i = 0; i < 5; i++){int isExchange = 0;for(j = i+1; j < 5; j++){if(a[i] < a[j]){temp = a[i];a[i] = a[j];a[j] = temp;isExchange = 1;}cmpCount++;if(!isExchange){break;}}}for(i = 0; i < 5; i++){printf("%d ", a[i]);}printf("\n");printf("the biggest num is %d\n", a[0]);printf("the second big num is %d\n", a[1]);printf("the compare Count is %d\n", cmpCount);return 0;}




0 0
原创粉丝点击