zoukankan      html  css  js  c++  java
  • 基础算法之查找数组中第二小的元素

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

    // 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
    "); 
        else
            printf("The smallest element is %d and second "
                "Smallest element is %d
    ", 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; 
    } 
  • 相关阅读:
    JSP
    Cookie
    HTTP
    Android布局属性详解剖析
    布局填充器的三种写法
    Linux笔记
    修改设置中数据流量小部件开关跟设置中流量开关同步
    adb 获取手机值
    java 中读取本地文件中字符
    android动画效果编程基础--Android Animation
  • 原文地址:https://www.cnblogs.com/jukaiit/p/11901854.html
Copyright © 2011-2022 走看看