# minimum_difference_in_array_of_unique_integers_v1.c

Aug 20th, 2020 (edited)
235
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
1. /*
2.
3.     minimum_difference_in_array_of_unique_integers_v1.c
4.
7.
8.     https://www.geeksforgeeks.org/find-minimum-difference-pair/
9.
10.
11.     You can find all my C programs at Dragan Milicev's pastebin:
12.
13.     https://pastebin.com/u/dmilicev
14.
15. */
16.
17. #include <stdio.h>
18. #include <limits.h>     // for INT_MAX
19.
20. // Returns minimum difference between any pair
21. int findMinDiff(int arr[], int n, int *first, int *second)
22. {
23.     int i, j, diff = INT_MAX;   // Initialize difference as infinite
24.
25.     // Find the min diff by comparing difference of all possible pairs in given array
26.     for (i=0; i<n-1; i++)
27.         for (j=i+1; j<n; j++)
28.             if (abs(arr[i] - arr[j]) < diff)
29.             {
30.                 diff = abs(arr[i] - arr[j]);
31.
32.                 if(arr[i] < arr[j])
33.                 {
34.                     *first = arr[i];
35.                     *second = arr[j];
36.                 }
37.                 else
38.                 {
39.                     *first = arr[j];
40.                     *second = arr[i];
41.                 }
42.
43.                 printf("\n diff = %d \t first = %d \t second = %d\n", diff, *first, *second);
44.             }
45.
46.     return diff;                // Return min diff
47. }
48.
49. int main(void)
50. {
51.     int arr[] = {67,33,45,2,89,120,52,309,21,101,190,567,985,774,8,631,99,1234,15,590};
52.     int first=1, second=2;
53.     int diff;
54.     int n = sizeof(arr)/sizeof(arr[0]);
55.
56.     diff=findMinDiff(arr, n, &first, &second);
57.
58. /*
59.     // Be careful:
60.     // Calling the findMinDiff() function inside the printf() function does not work well !!!
61.     printf("\n Minimum difference is %d between %d and %d \n",
62.             findMinDiff(arr, n, &first, &second), first, second );
63. */
64.     printf("\n Minimum difference among %d unique integers is %d between %d and %d \n",
65.             n, diff, first, second );
66.
67.     return 0;
68.
69. } // main()
70.