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?
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?
yes, i realize that...
Sort it. Walk it. Subtract them as you go.
Quzah.
Hope is the first step on the road to disappointment.
would anyone mind explaining how to do it?
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.
Last edited by ominub; 10-20-2009 at 07:42 PM. Reason: clarification
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.)
Last edited by tabstop; 10-20-2009 at 07:45 PM.
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.
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.
My homepage
Advice: Take only as directed - If symptoms persist, please see your debugger
Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"
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