Encuentre los elementos más pequeños y el segundo más pequeño en una array

Escriba un programa eficiente en C para encontrar el elemento más pequeño y el segundo más pequeño en una array.
 

Ejemplo

Input:  arr[] = {12, 13, 1, 10, 34, 1}
Output: The smallest element is 1 and 
        second Smallest element is 10

Método 1 (enfoque simple)
Una solución simple es ordenar la array en orden creciente. Los dos primeros elementos de la array ordenada serían los dos elementos más pequeños. En este enfoque, si el elemento más pequeño está presente más de una vez, tendremos que usar un ciclo para imprimir los elementos únicos más pequeños y los segundos más pequeños. 

La complejidad temporal de esta solución es O(n log n).

C++

//C++ simple approach to print smallest
//and second smallest element.
#include<bits/stdc++.h>
using namespace std;
int main() {
int arr[]={111, 13, 25, 9, 34, 1};
int n=sizeof(arr)/sizeof(arr[0]);
//sorting the array using
//in-built sort function
sort(arr,arr+n);
//printing the desired element
cout<<"smallest element is "<<arr[0]<<endl;
cout<<"second smallest element is "<<arr[1];
return 0;
}
 
//this code is contributed by Machhaliya Muhammad

Java

/*package whatever //do not write package name here */
 
import java.io.*;
import java.util.*;
 
class GFG {
//Java simple approach to print smallest
//and second smallest element.
 
// Driver Code
public static void main(String args[])
{
    int arr[]={111, 13, 25, 9, 34, 1};
    int n=arr.length;
   
    // sorting the array using
    // in-built sort function
    Arrays.sort(arr);
   
    // printing the desired element
    System.out.println("smallest element is "+arr[0]);
    System.out.println("second smallest element is "+arr[1]);
}
}
 
// This code is contributed by shinjanpatra

Python3

# Python3 simple approach to print smallest
# and second smallest element.
 
# driver code
 
arr = [111, 13, 25, 9, 34, 1]
n = len(arr)
# sorting the array using
# in-built sort function
arr.sort()
 
# printing the desired element
print("smallest element is "+str(arr[0]))
print("second smallest element is "+str(arr[1]))
 
# This code is contributed by shinjanpatra

Javascript

<script>
 
// JavaScript simple approach to print smallest
// and second smallest element.
 
// driver code
 
let arr = [111, 13, 25, 9, 34, 1];
let n = arr.length;
// sorting the array using
// in-built sort function
arr.sort();
 
// printing the desired element
document.write("smallest element is "+arr[0],"</br>");
document.write("second smallest element is "+arr[1],"</br>");
 
// This code is contributed by shinjanpatra
 
</script>
Producción

smallest element is 1
second smallest element is 9

Complejidad temporal: O(N*logN)
Espacio auxiliar: O(1)

Método 2:
una mejor solución es escanear la array dos veces. En el primer recorrido encuentre el elemento mínimo. Sea este elemento x. En el segundo recorrido, encuentre el elemento más pequeño mayor que x.

Usando este método, podemos superar el problema del Método 1 que ocurre cuando el elemento más pequeño está presente en una array más de una vez.
La solución anterior requiere dos recorridos de la array de entrada. 

C++

// C++ program to find smallest and
// second smallest element in array
#include <bits/stdc++.h>
using namespace std;
int main()
{
    int arr[] = {12, 13, 1, 10, 34, 1};
    int n = sizeof(arr) / sizeof(arr[0]);
    int smallest = INT_MAX;
    // traversing the array to find
    // smallest element.
    for (int i = 0; i < n; i++)
    {
        if (arr[i] < smallest)
        {
            smallest = arr[i];
        }
    }
    cout << "smallest element is: " << smallest << endl;
 
    int second_smallest = INT_MAX;
 
    // traversing the array to find second smallest element
    for (int i = 0; i < n; i++)
    {
        if (arr[i] < second_smallest && arr[i] > smallest)
        {
            second_smallest = arr[i];
        }
    }
    cout << "second smallest element is: " << second_smallest << endl;
    return 0;
}
 
// This code is contributed by Machhaliya Muhamma

Java

// Java program to find smallest and
// second smallest element in array
class GFG {
    public static void main(String args[])
    {
        int arr[] = { 12, 13, 1, 10, 34, 1 };
        int n = arr.length;
        int smallest = Integer.MAX_VALUE;
        // traversing the array to find
        // smallest element.
        for (int i = 0; i < n; i++) {
            if (arr[i] < smallest) {
                smallest = arr[i];
            }
        }
        System.out.println("smallest element is: "
                           + smallest);
 
        int second_smallest = Integer.MAX_VALUE;
 
        // traversing the array to find second smallest
        // element
        for (int i = 0; i < n; i++) {
            if (arr[i] < second_smallest
                && arr[i] > smallest) {
                second_smallest = arr[i];
            }
        }
        System.out.println("second smallest element is: "
                           + second_smallest);
    }
}
 
// This code is contributed by Lovely Jain

C#

// C# program to find smallest and
// second smallest element in array
 
using System;
 
public class GFG
{
  static public void Main ()
  {
    int[] arr = { 12, 13, 1, 10, 34, 1 };
    int n = arr.Length;
    int smallest = Int32.MaxValue;
    // traversing the array to find
    // smallest element.
    for (int i = 0; i < n; i++)
    {
      if (arr[i] < smallest)
      {
        smallest = arr[i];
      }
    }
    Console.WriteLine("smallest element is: " + smallest);
 
    int second_smallest = Int32.MaxValue;
 
    // traversing the array to find second smallest
    // element
    for (int i = 0; i < n; i++)
    {
      if (arr[i] < second_smallest && arr[i] > smallest)
      {
        second_smallest = arr[i];
      }
    }
    Console.WriteLine("second smallest element is: " + second_smallest);
  }
}
 
// This code is contributed by kothavvsaakash

Javascript

<script>
 
// Javascript program to find smallest and
// second smallest elements
 
function solution( arr, arr_size)
{
  let first = Number.MAX_VALUE,
        second = Number.MAX_VALUE;
 
  /* There should be atleast two elements */
  if (arr_size < 2)
  {
    document.write(" Invalid Input ");
    return;
  }
   /* find the smallest element */
  for (let i = 0; i < arr_size ; i ++)
  {
    if (arr[i] < first){
      first = arr[i];
    }
  }
   /* find the second smallest element */
   for (let i = 0; i < arr_size ; i ++){
    if (arr[i] < second && arr[i] > first){
      second = arr[i];
    }
  }
  if (second == Number.MAX_VALUE )
    document.write("There is no second smallest element\n");
  else
    document.write("The smallest element is " + first + " and second "+
      "Smallest element is " + second +'\n');
}
 
 
  // Driver program
   
  let arr = [ 12, 13, 1, 10, 34, 1 ];
  let n = arr.length;
  solution(arr, n);
   
</script>
Producción

smallest element is: 1
second smallest element is: 10
 

Complete Interview Preparation - GFG

Complejidad temporal: O(N)
Espacio auxiliar: O(1)

Una solución eficiente puede encontrar los dos elementos mínimos en un recorrido. A continuación se muestra el algoritmo completo.
Algoritmo: 

1) Initialize both first and second smallest as INT_MAX
   first = second = INT_MAX
2) Loop through all the elements.
   a) If the current element is smaller than first, then update first 
       and second. 
   b) Else if the current element is smaller than second then update 
    second

A continuación se muestra la implementación del enfoque anterior:

C++

// C++ program to find smallest and
// second smallest elements
#include <bits/stdc++.h>
using namespace std; /* For INT_MAX */
 
void print2Smallest(int arr[], int arr_size)
{
    int i, first, second;
 
    /* There should be atleast two elements */
    if (arr_size < 2)
    {
        cout<<" 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)
        cout << "There is no second smallest element\n";
    else
        cout << "The smallest element is " << first << " and second "
            "Smallest element is " << second << endl;
}
 
/* Driver code */
int main()
{
    int arr[] = {12, 13, 1, 10, 34, 1};
    int n = sizeof(arr)/sizeof(arr[0]);
    print2Smallest(arr, n);
    return 0;
}
 
// This is code is contributed by rathbhupendra

C

// 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;
}

Java

// Java program to find smallest and second smallest elements
import java.io.*;
 
class SecondSmallest
{
    /* Function to print first smallest and second smallest
      elements */
    static void print2Smallest(int arr[])
    {
        int first, second, arr_size = arr.length;
 
        /* There should be atleast two elements */
        if (arr_size < 2)
        {
            System.out.println(" Invalid Input ");
            return;
        }
 
        first = second = Integer.MAX_VALUE;
        for (int 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 == Integer.MAX_VALUE)
            System.out.println("There is no second" +
                               "smallest element");
        else
            System.out.println("The smallest element is " +
                               first + " and second Smallest" +
                               " element is " + second);
    }
 
    /* Driver program to test above functions */
    public static void main (String[] args)
    {
        int arr[] = {12, 13, 1, 10, 34, 1};
        print2Smallest(arr);
    }
}
/*This code is contributed by Devesh Agrawal*/

Python3

# Python program to find smallest and second smallest elements
import math
 
def print2Smallest(arr):
 
    # There should be atleast two elements
    arr_size = len(arr)
    if arr_size < 2:
        print ("Invalid Input")
        return
 
    first = second = math.inf
    for i in range(0, arr_size):
 
        # 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
        elif (arr[i] < second and arr[i] != first):
            second = arr[i];
 
    if (second == math.inf):
        print ("No second smallest element")
    else:
        print ('The smallest element is',first,'and', \
              ' second smallest element is',second)
 
# Driver function to test above function
arr = [12, 13, 1, 10, 34, 1]
print2Smallest(arr)
 
# This code is contributed by Devesh Agrawal

C#

// C# program to find smallest
// and second smallest elements
using System;
 
class GFG
{
     
    /* Function to print first smallest
     and second smallest elements */
    static void print2Smallest(int []arr)
    {
        int first, second, arr_size = arr.Length;
 
        /* There should be atleast two elements */
        if (arr_size < 2)
        {
            Console.Write(" Invalid Input ");
            return;
        }
 
        first = second = int.MaxValue;
         
        for (int 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.MaxValue)
            Console.Write("There is no second" +
                            "smallest element");
        else
            Console.Write("The smallest element is " +
                            first + " and second Smallest" +
                            " element is " + second);
    }
 
    /* Driver program to test above functions */
    public static void Main()
    {
        int []arr = {12, 13, 1, 10, 34, 1};
        print2Smallest(arr);
    }
}
 
// This code is contributed by Sam007

PHP

<?php
// PHP  program to find smallest and
// second smallest elements
 
function print2Smallest($arr, $arr_size)
{
    $INT_MAX = 2147483647;
     
    /* There should be atleast
       two elements */
    if ($arr_size < 2)
    {
        echo(" 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)
        echo("There is no second smallest element\n");
    else
        echo "The smallest element is ",$first
             ," and second Smallest element is "
                                     , $second;
}
 
// Driver Code
$arr = array(12, 13, 1, 10, 34, 1);
$n = count($arr);
print2Smallest($arr, $n)
 
// This code is contributed by Smitha
?>

Javascript

<script>
 
// Javascript program to find smallest and
// second smallest elements
 
function print2Smallest( arr, arr_size)
{
    let i, first, second;
 
    /* There should be atleast two elements */
    if (arr_size < 2)
    {
        document.write(" Invalid Input ");
        return;
    }
 
    first=Number.MAX_VALUE ;
    second=Number.MAX_VALUE ;
    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 == Number.MAX_VALUE )
        document.write("There is no second smallest element\n");
    else
        document.write("The smallest element is " + first + " and second "+
            "Smallest element is " + second +'\n');
}
 
 
    // Driver program
     
    let arr = [ 12, 13, 1, 10, 34, 1 ];
    let n = arr.length;
    print2Smallest(arr, n);
     
</script>
Producción

The smallest element is 1 and second Smallest element is 10

Se puede usar el mismo enfoque para encontrar los elementos más grandes y los segundos más grandes en una array.

Complejidad temporal: O(n)
Espacio auxiliar: O(1)
 

Artículo relacionado:  
Elementos mínimos y segundos mínimos usando comparaciones mínimas
Escriba comentarios si encuentra algún error en el programa/algoritmo anterior u otras formas de resolver el mismo problema.

Publicación traducida automáticamente

Artículo escrito por GeeksforGeeks-1 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *