求第一,第二,第三大的值
#include <stdio.h> int main(){ int arr1[10]={1,3,2,5,4,7,5,6,9}; int max =0; int second_max =0; int third_max =0; for(int a=0;a<10;a++){ if(arr1[a] > max){ third_max =second_max; second_max =max; max =arr1[a]; } } printf("first MAX = %d \n",max); printf("second MAX = %d \n",second_max); printf("third MAX = %d \n",third_max); return 0; } /* 请按任意键继续. . . first MAX = 9 second MAX = 7 third MAX = 5 请按任意键继续. . . */
逆置数组
#include <stdio.h> int main(){ int arr1[10]={1,3,2,5,4,7,5,6,9}; printf("-------原始元素--------\n"); for(int a=0;a<10;a++){ printf("arr1[%d]=%d\n",a,arr1[a]); } int low=0; int high=9; int tmp_var; while(low<high){ tmp_var =arr1[low]; arr1[low] =arr1[high]; arr1[high] =tmp_var; low++; high--; } printf("-------分割线--------\n"); for(int a=0;a<10;a++){ printf("arr1[%d]=%d\n",a,arr1[a]); } return 0; } /* 请按任意键继续. . . -------原始元素-------- arr1[0]=1 arr1[1]=3 arr1[2]=2 arr1[3]=5 arr1[4]=4 arr1[5]=7 arr1[6]=5 arr1[7]=6 arr1[8]=9 arr1[9]=0 -------分割线-------- arr1[0]=0 arr1[1]=9 arr1[2]=6 arr1[3]=5 arr1[4]=7 arr1[5]=4 arr1[6]=5 arr1[7]=2 arr1[8]=3 arr1[9]=1 请按任意键继续. . . */
冒泡法
#include <stdio.h> int main(){ int arr1[10]={1,3,9,5,4,7,0,6,8,2}; int tmp=0; int num=0; for(int i=0;i<10;i++){ for(int j=0;j<10-i;j++){ if(arr1[j]>arr1[j+1]){ //更改这个为小于号,数组的排序也会变 tmp =arr1[j]; arr1[j] =arr1[j+1]; arr1[j+1] = tmp; num++; } } } printf("-------冒泡法排序用了%d次--------\n",num); for(int a=0;a<10;a++){ printf("arr1[%d]=%d\n",a,arr1[a]); } return 0; } /* 请按任意键继续. . . -------冒泡法排序用了20次-------- arr1[0]=0 arr1[1]=1 arr1[2]=2 arr1[3]=3 arr1[4]=4 arr1[5]=5 arr1[6]=6 arr1[7]=7 arr1[8]=8 arr1[9]=9 请按任意键继续. . . */
时间: 2024-10-10 18:57:44