Closest numbers from a list of unsorted integers - GeeksforGeeks

08 Apr, 2021
Given a list of distinct unsorted integers, find the pair of elements that have the smallest absolute difference between them? If there are multiple pairs, find them all.Examples:  
Input : arr[] = {10, 50, 12, 100}
Output : (10, 12)
The closest elements are 10 and 12

Input : arr[] = {5, 4, 3, 2}
Output : (2, 3), (3, 4), (4, 5)
 
This problem is mainly an extension of Find minimum difference between any two elements. 
Sort the given array.Find minimum difference of all pairs in linear time in sorted array.Traverse sorted array one more time to print all pairs with minimum difference obtained in step 2.
Sort the given array.
Find minimum difference of all pairs in linear time in sorted array.
Traverse sorted array one more time to print all pairs with minimum difference obtained in step 2.
 
C++
Java
Python3
C#
PHP
Javascript
// CPP program to find minimum difference// an unsorted array.#include<bits/stdc++.h>using namespace std; // Returns minimum difference between any// two pair in arr[0..n-1]void printMinDiffPairs(int arr[], int n){   if (n <= 1)      return;    // Sort array elements   sort(arr, arr+n);    // Compare differences of adjacent   // pairs to find the minimum difference.   int minDiff = arr[1] - arr[0];   for (int i = 2 ; i < n ; i++)      minDiff = min(minDiff, arr[i] - arr[i-1]);    // Traverse array again and print all pairs   // with difference as minDiff.   for (int i = 1; i < n; i++)      if ((arr[i] - arr[i-1]) == minDiff)         cout << "(" << arr[i-1] << ", "              << arr[i] << "), ";} // Driver codeint main(){    int arr[] = {5, 3, 2, 4, 1};    int n = sizeof(arr) / sizeof(arr[0]);    printMinDiffPairs(arr, n);    return 0;}
// Java program to find minimum// difference an unsorted array.import java.util.*; class GFG{       // Returns minimum difference between  // any two pair in arr[0..n-1]  static void printMinDiffPairs(int arr[], int n)  {    if (n <= 1)      return;         // Sort array elements    Arrays.sort(arr);         // Compare differences of adjacent    // pairs to find the minimum difference.    int minDiff = arr[1] - arr[0];    for (int i = 2; i < n; i++)      minDiff = Math.min(minDiff, arr[i] - arr[i-1]);          // Traverse array again and print all pairs    // with difference as minDiff.    for ( int i = 1; i < n; i++)     {        if ((arr[i] - arr[i-1]) == minDiff)        {           System.out.print("(" + arr[i-1] + ", "                           + arr[i] + ")," );        }                        }  }       // Driver code  public static void main (String[] args)  {    int arr[] = {5, 3, 2, 4, 1};    int n = arr.length;    printMinDiffPairs(arr, n);  }} // This code is contributed by Ansu Kumari
# Python3 program to find minimum# difference in an unsorted array. # Returns minimum difference between# any two pair in arr[0..n-1]def printMinDiffPairs(arr , n):    if n <= 1: return     # Sort array elements    arr.sort()         # Compare differences of adjacent    # pairs to find the minimum difference.    minDiff = arr[1] - arr[0]    for i in range(2 , n):        minDiff = min(minDiff, arr[i] - arr[i-1])     # Traverse array again and print all    # pairs with difference as minDiff.    for i in range(1 , n):        if (arr[i] - arr[i-1]) == minDiff:            print( "(" + str(arr[i-1]) + ", "                 + str(arr[i]) + "), ", end = '') # Driver codearr = [5, 3, 2, 4, 1]n = len(arr)printMinDiffPairs(arr , n) # This code is contributed by Ansu Kumari
// C# program to find minimum// difference an unsorted array.using System; class GFG{     // Returns minimum difference between// any two pair in arr[0..n-1]static void printMinDiffPairs(int []arr, int n){    if (n <= 1)    return;         // Sort array elements    Array.Sort(arr);         // Compare differences of adjacent    // pairs to find the minimum difference.    int minDiff = arr[1] - arr[0];    for (int i = 2; i < n; i++)    minDiff = Math.Min(minDiff, arr[i] - arr[i-1]);         // Traverse array again and print all pairs    // with difference as minDiff.    for ( int i = 1; i < n; i++)    {        if ((arr[i] - arr[i-1]) == minDiff)        {        Console.Write(" (" + arr[i-1] + ", "                          + arr[i] + "), " );        }                }}     // Driver codepublic static void Main (){    int []arr = {5, 3, 2, 4, 1};    int n = arr.Length;    printMinDiffPairs(arr, n);}} // This code is contributed by vt_m
<?php//PHP program to find minimum difference// an unsorted array. // Returns minimum difference between any// two pair in arr[0..n-1]function printMinDiffPairs($arr, $n){    if ($n <= 1)        return;         // Sort array elements    sort($arr);         // Compare differences of adjacent    // pairs to find the minimum    // difference.    $minDiff = $arr[1] - $arr[0];         for ($i = 2 ; $i < $n ; $i++)        $minDiff = min($minDiff, $arr[$i]                            - $arr[$i-1]);         // Traverse array again and print all    // pairs with difference as minDiff.    for ($i = 1; $i < $n; $i++)        if (($arr[$i] - $arr[$i-1]) ==                                $minDiff)            echo "(" , $arr[$i-1] , ", ",                        $arr[$i] , "), ";} // Driver code    $arr = array(5, 3, 2, 4, 1);    $n = sizeof($arr);    printMinDiffPairs($arr, $n);     // This code is contributed by ajit.?>
<script> // JavaScript program to find minimum// difference an unsorted array.   // Returns minimum difference between  // any two pair in arr[0..n-1]  function printMinDiffPairs(arr, n)  {    if (n <= 1)      return;           // Sort array elements    arr.sort();           // Compare differences of adjacent    // pairs to find the minimum difference.    let minDiff = arr[1] - arr[0];    for (let i = 2; i < n; i++)      minDiff = Math.min(minDiff, arr[i] - arr[i-1]);            // Traverse array again and print all pairs    // with difference as minDiff.    for ( let i = 1; i < n; i++)     {        if ((arr[i] - arr[i-1]) == minDiff)        {           document.write("(" + arr[i-1] + ", "                           + arr[i] + ") , " );        }                        }  }        // Driver code                 let arr = [5, 3, 2, 4, 1];    let n = arr.length;    printMinDiffPairs(arr , n); </script>
Output: 
(1, 2), (2, 3), (3, 4), (4, 5), 
Does above program handle duplicates? The cases like {x, x, x} are not handled by above program. For this case, the expected output (x, x), (x, x), (x, x), but above program prints (x, x), (x, x) 
jit_t
splevel62
Amazon
Arrays
Searching
Sorting
Amazon
Arrays
Searching
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Next Greater Element
Window Sliding Technique
Count pairs with given sum
Program to find sum of elements in a given array
Reversal algorithm for array rotation
Binary Search
Median of two sorted arrays of different sizes
Most frequent element in an array
Find the index of an array element in Java
Count number of occurrences (or frequency) in a sorted array