# Thread: finding the two closest numbers in an array

1. ## finding the two closest numbers in an array

i have a sorted array of integers and i'm trying to find the two closest numbers. anyone have an idea of how to do this?

2. Originally Posted by ominub
anyone have an idea of how to do this?
Yep. It involves comparing numbers.

Quzah.

3. yes, i realize that...

4. Sort it. Walk it. Subtract them as you go.

Quzah.

5. would anyone mind explaining how to do it?

6. Originally Posted by quzah
Sort it. Walk it. Subtract them as you go.

i've gotten this far, but i cant figure out how to store the smallest number while i compare it to the rest of the results.
the whole point is printing the rwo closest numbers so it will also have to remember those two numbers.
i'm having a hard time wrapping my mind around it.

7. Well, you said how. Store the smallest number (in a variable called, ooh, "smallest" maybe). (EDIT based on your edit: So you need to store two numbers (and therefore in two variables) in addition to the "smallest" above.)

8. There are no special C functions for doing this, so code it up like you would do it by hand.

Say your values were: 1,3,5,6, 9. How would you find the two numbers that are closest?

1 - 3 = diff = mingap = 2

3 - 1 is the same as 1 - 3 for gap, so we only need to subtract with the adjacent, larger, number.

3 - 5 = diff not lower than mingap, either.

5 - 6 = diff = new mingap of 1

As a practical matter, I'd prefer to work down the array values, to avoid any negative numbers or absolute value stuff.

9. Imagine you were told that you would be shown a series of cards with numbers on them. Each number is to be greater than the next. You will be shown 50 numbers, each one for as long as you require, but only one at a time. Your task is to identify the two closest together numbers. You may not write anything down, but you're free to use a basic calculator if you wish.

Would you be able to identify the closest two numbers after all cards have been shown to you?
This is exactly the kind of simple problem that anyone hoping to be a programmer should definitely be able to solve. If you can't come up with a logical solution then you're just not applying your mind to the problem. Think about it for a while longer until you eventually solve it on your own.

If you then know how to solve the problem but can't code up a solution because you're new to C then that's fine, just give it a shot anyway and post what you get.

10. As everybody said above this is the pusdocode for it

As array is sorted then

Code:
```For i 0 to N - 1
TEMP_DIFF = ARR[i+1] - ARR[i]

if (TEMP_DIFF < DIFF)
START_ELEMENT = i
END_ELEMENT     = i  +  1
endif

DIFF = TEMP_DIFF```