Tuesday, March 21, 2006

Sorting an array based on the index

I was speaking to Harsha this evening and he asked me an interesting question: How to sort an array...? This question sounds simple enough but the question is not yet complete - the output of the sort should not be a sorted array of the original elements, but should be another array that has the sorted indices refering back to the original array.

For example take a 5 element array:

A[0] = 55
A[1] = 1
A[2] = 75
A[3] = 11
A[4] = 27

If I were to sort this array in ascending order then it would have resulted in

A[0] = 1
A[1] = 11
A[2] = 27
A[3] = 55
A[4] = 75

Now to sort the indices, if you have another array named as B[] then B[] should contain the sorted indices of A[] as follows (ascending order):

B[0] = 1
B[1] = 3
B[2] = 4
B[3] = 0
B[4] = 2

The solution is pretty straight forward - Instead of sorting based on A[i] just sort based on A[B[i]]. Use your favorite sorting algorithm and the runtime will be as bad as whatever sorting algorithm you use. For this simple case lets use Bubble sort:

for (i=0; i<5; i++) B[i] = i;

for (i=0; i<5; i++)
for (j=i; j<5; i++)
if (A[B[i]] > A[B[j]])
swap B[i] and B[j]

0 Comments:

Post a Comment

<< Home