3.找出下列整型数组中最大和最小值及其所在位置i.
int a[] = {5,-9,32,77,64,-24,14,0,21,45};
方法1:
int a[] = {5,-9,32,77,64,-24,14,0,21,45};
int max=0;
int min=0;
int index = 0;
for (int i =0; i<9; i++) {
if (max<a[i]) {
max = a[i];
index = i;
}
}
printf("max=%d",max);
printf("\nmax位置在:%d\n",index);
for (int i =0; i<9; i++) {
if (min>a[i]) {
min = a[i];
index = i;
}
}
printf("min=%d",min);
printf("\nmin位置在:%d\n",index);
方法2:
int a[] = {5,-9,32,77,64,-24,14,0,21,45};
int imax = 0;
int imin = 0;
int max = 0;
int min = 0;
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9 - i; j++) {
if (a[j] > a[j+1]) {
if (a[j] > max) {
imax = j;
max = a[j];
}
if (a[j+1] < min) {
imin = j+1;
min = a[j+1];
}
int temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
else{
if (a[j+1] > max) {
imax = j+1;
max = a[j+1];
}
if (a[j] < min) {
imin = j;
min = a[j];
}
}
}
}
printf("max = %d imax = %d\n",max,imax);
printf("min = %d imin = %d\n",min,imin);
冒泡排序法找数组中最大,最小值及其所在位置
最新推荐文章于 2024-06-29 18:45:52 发布