Home Ask Login Register

Developers Planet

Your answer is one click away!

racarate February 2016

How to k-shuffle an array with STL?

I am testing an algorithm that sorts a k-sorted array (every element is at most k-positions away from its correct sorted position).

I am having a hard time generating test data -- I can't randomly swap elements by k-positions because I may end up swapping an element twice. I could track which elements I swapped but then I need O(N) space. I could also use a random-heap of size k + 1, but that sounds silly.

Is there anything built into the STL that can help me with this? This seems like a common problem, but my brief research only turned up algorithms for total shuffles (I think STL implements Fisher-Yates).


Öö Tiib February 2016

It feels odd problem since preparing random test data does not need to be ultra efficient, also the data may be usually whatever. You can have the test values as correct positions of those elements or pairs that give range of correct positions. For example array of pairs:

  1. 1,1
  2. 2,4
  3. 2,4
  4. 2,4
  5. 5,6
  6. 5,6
  7. 7,7

Store the state of random generator somewhere.

Choose two random elements whose position is not more than k positions away of original position (or range) of other and swap. Repeat that N times and your test data is ready.

If you need to get same sequence later then restore the random generator state and repeat the algorithm.

Post Status

Asked in February 2016
Viewed 1,476 times
Voted 5
Answered 1 times


Leave an answer

Quote of the day: live life