冒泡排序法找数组中最大,最小值及其所在位置

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);

发布了40 篇原创文章 · 获赞 1 · 访问量 3万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览