negru

Write a program that will print two closest pair integers in an array (if there are more than one pair with the same distance, then print all pairs).

``````//Example:
6 -3 8 0 5

//The closest numbers:
5 6 -> difference is 1
``````

In the following program I am using bubble sort algorithm, but don't know how to find the difference for each pair:

``````#include <stdio.h>
#include <stdlib.h>

void bubbleSort(int *arr, int n)
{
int i,j;
int min=0;
for(i=0;i<n-1;i++)
{
for(j=0;j<n-i-1;j++)
{
if(arr[j] > arr[j+1])
{
int temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
//for each "arr[j]","arr[j+1]"-> check "min"
}
}
}

int main()
{
int i,n;
int *arr;

do
{
printf("n=");
scanf("%d", &n);
}
while (n < 1);

arr = (int *)malloc(n * sizeof(int));
for (i = 0; i < n; i++)
{
printf("%d. number: ", i + 1);
scanf("%d",&arr[i]);
}

bubbleSort(arr, n);

for(i=0;i<n;i++)
printf("\n%d",arr[i]);

free(arr);
return 0;
}
``````

rubberman 1,355

Create a separate results array, one element less than the array that contains the numbers. Iterate through the array and store the deltas between each pair to the results array. Then you can easily find which pair(s) are closest, as well as there are any other matches. Let's say that your data array gets the values 0, 1, 4, 5, 6. Your results array should end up with the values 1, 3, 1, 1. Now you can easily see which items have the same distance as you put it.

I will leave the coding for this algorithm in your capable hands. I will help like this with schoolwork, or help you figure out what is wrong with your code, but I won't give you the answers... :-)