Hi!

I have an array of doubles that I map to a hashmap to keep track of the indices of the elements. I want to be able to sort the array and still keep track of the indices and thats no problem as long as the elements are distinct. But when I encounter 2 or more elements in the array that are equal my whole scheme fails since they will get the same index.

I see two solutions to the problem:

1: Find a way to generate better keys for the elements (dont know how to do this)

or

2. Throw out the hashmap and apply a new datastructure that actually does what I want. Anyone got any suggestions on this? Im not to excited about writing my own specific datastructure for this since it's overall a fairly small task that Im working on.

Thanks for any help!

Slim

You mean you want to sort the array without actually swapping array values? I have done that before but used a second array of intgers that represent the array indices.

float data[5] = {3,1,4,9,2};
int indices[5] = {0,1,2,3,4};

// sort the data
for(int i = 0; i < 4; i++)
{
  for(int j = i+1; j < 5; j++)
  {
     if( data[indices[i]] < data[indices[j]] )
     {
        int temp = indices[i];
        indices[i] = indices[j];
        indices[j] = temp;
     }
  }
}

// now display the values
for(int i = 0; i < 5; i++)
   printf("%f\n", data[indices[i]]);

This technique is a good way to sort large 2d arrays also because it greatly reduces the number of items to be swapped during sorting. The contents of the original array are unchanged.

Edited 6 Years Ago by Ancient Dragon: n/a

Looks promising! I'll try that out and get back to you, thanks.

Worked fine for me, thanks!. Marking thread as solved.

This question has already been answered. Start a new discussion instead.