手记

C语言指针入门:从零掌握核心概念

zhenghui@zhlinux:~/codeProject/11指针$
zhenghui@zhlinux:~/codeProject/11指针$ cat find_tow_larget.c
#include <stdio.h>
#define ARRAY_SIZE(array) ((int) (sizeof(array) / sizeof(array[0]) ))

/*
 * 查找最大值和第二大值
 * */
void find_tow_largest(int a[],int n,int *largest,int *second_largest)
{

    // 1、寻找最大值
    *largest = a[0];
    // 记录最大值的位置
    int maxIndex = 0;

    for(int i = 1;i<n;i++)
    {
        if(*largest < a[i])
        {
            *largest = a[i];

            maxIndex = i;
        }
    }

    // 2、寻找第二大值

    // 将最大值替换为最小值
    a[maxIndex] = -1;
    *second_largest = a[0];

    for(int i = 1;i<n;i++)
    {
        if(*second_largest < a[i])
        {
            *second_largest = a[i];
        }
    }

}

/*
 * 通过排序查找最大值和第二大值
 * */
void find_sort_tow_largest(int a[],int n,int *largest,int *second_largest)
{

    // 1、初始化排序
    for(int i = 1;i<n;i++)
    {
        if(a[i-1] > a[i])
        {
            int j = i - 1;
            int temp = a[i];

            while(j > -1 && temp < a[j])
            {
                a[j+1] = a[j];
                j--;
            }

            a[j+1] = temp;
        }
    }

    *largest = a[n-1];
    *second_largest = a[n-2];

}

int main()
{
    int a[] = {1,5,2,4,7,5,8,234};

    int n = ARRAY_SIZE(a);

    int largest,second_largest;

    //find_tow_largest(a,n,&largest,&second_largest);
    find_sort_tow_largest(a,n,&la
rgest,&second_largest);

    printf("最大值:%d,次大值:%d\n",largest,second_largest);

    return 0;
}
0人推荐
随时随地看视频
慕课网APP