基础算法之查找数组中第二小的元素

最后都变了- 提交于 2019-12-05 03:13:56

找到数组中,第二小的元素

 

 

// C program to find smallest and second smallest elements 
#include <stdio.h> 
#include <limits.h> /* For INT_MAX */ 

void print2Smallest(int arr[], int arr_size) 
{ 
    int i, first, second; 

    /* There should be atleast two elements */
    if (arr_size < 2) 
    { 
        printf(" Invalid Input "); 
        return; 
    } 

    first = second = INT_MAX; 
    for (i = 0; i < arr_size ; i ++) 
    { 
        /* If current element is smaller than first 
        then update both first and second */
        if (arr[i] < first) 
        { 
            second = first; 
            first = arr[i]; 
        } 

        /* If arr[i] is in between first and second 
        then update second */
        else if (arr[i] < second && arr[i] != first) 
            second = arr[i]; 
    } 
    if (second == INT_MAX) 
        printf("There is no second smallest element\n"); 
    else
        printf("The smallest element is %d and second "
            "Smallest element is %d\n", first, second); 
} 

/* Driver program to test above function */
int main() 
{ 
    int arr[] = {12, 13, 1, 10, 34, 1}; 
    int n = sizeof(arr)/sizeof(arr[0]); 
    print2Smallest(arr, n); 
    return 0; 
} 

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!