Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- minimum_difference_in_array_of_unique_integers_v1.c
- Task:
- https://web.facebook.com/photo/?fbid=350432899315771&set=gm.3403903939630572
- https://www.geeksforgeeks.org/find-minimum-difference-pair/
- You can find all my C programs at Dragan Milicev's pastebin:
- https://pastebin.com/u/dmilicev
- */
- #include <stdio.h>
- #include <limits.h> // for INT_MAX
- // Returns minimum difference between any pair
- int findMinDiff(int arr[], int n, int *first, int *second)
- {
- int i, j, diff = INT_MAX; // Initialize difference as infinite
- // Find the min diff by comparing difference of all possible pairs in given array
- for (i=0; i<n-1; i++)
- for (j=i+1; j<n; j++)
- if (abs(arr[i] - arr[j]) < diff)
- {
- diff = abs(arr[i] - arr[j]);
- if(arr[i] < arr[j])
- {
- *first = arr[i];
- *second = arr[j];
- }
- else
- {
- *first = arr[j];
- *second = arr[i];
- }
- printf("\n diff = %d \t first = %d \t second = %d\n", diff, *first, *second);
- }
- return diff; // Return min diff
- }
- int main(void)
- {
- int arr[] = {67,33,45,2,89,120,52,309,21,101,190,567,985,774,8,631,99,1234,15,590};
- int first=1, second=2;
- int diff;
- int n = sizeof(arr)/sizeof(arr[0]);
- diff=findMinDiff(arr, n, &first, &second);
- /*
- // Be careful:
- // Calling the findMinDiff() function inside the printf() function does not work well !!!
- printf("\n Minimum difference is %d between %d and %d \n",
- findMinDiff(arr, n, &first, &second), first, second );
- */
- printf("\n Minimum difference among %d unique integers is %d between %d and %d \n",
- n, diff, first, second );
- return 0;
- } // main()
Advertisement
Add Comment
Please, Sign In to add comment