# Sort array with difference

This is a discussion on Sort array with difference within the C Programming forums, part of the General Programming Boards category; Hello everybody, I have a question to ask, what is the efficient way to sort array according to difference of ...

1. ## Sort array with difference

Hello everybody,

I have a question to ask, what is the efficient way to sort array according to difference of elements?

Let's say I have array/vector

a = [0 2 3 6 8]; //which is sorted and start from 0.

But I want to sort by neighbor difference

abs(0-2) = 2 //difference between first and second elements in vector
abs(2-3) = 1 //difference between second and third elements in vector
abs(3-6) = 3
abs(6-8) = 2

Now sorted output:
abs(2-3) = 1
abs(0-2) = 2
abs(6-8) = 2
abs(3-6) = 3

make new vector from sorted:
a = [0 1 3 5 8] now their difference is accordance of sorted early vector.

If there is anything is not clear, please let me know I will do my best to explain more in details.
Any idea appreciated!
Thanks!

2. In C++ you could use set container - it would sort values for you. In C you can try different sorting algorithms and check which one of them is the most efficient (fastest) in this case.

3. I think you are on the wrong forum mate, this is C not C++.

4. As for the OP, post your attempt, this is not a homework service.

5. Originally Posted by claudiu
I think you are on the wrong forum mate, this is C not C++.
My fault, I've edited my post.

6. Thanks for responds, DRK.

I might try qsort though problem is in subtraction part, I need to go through all elements in order to subtract them, which made me post here to get some ideas.

NOTE claudiu: I am not expecting any code, just ideas. and beside it is not a homework or assignment of any kind. Just came across with problem and thought would be good to ask opinions.

Hoping to sort of find smarter way to do it!

7. Well to begin with you can easily extract the difference vector as you are reading in the data vector.

Then you could do a merge sort on the difference vector. You just need to ensure that you also save the original indexes so that you can print your original array in the correct order (if you are not allowed to rearrange that as well).