简体   繁体   中英

Sorting Mechanism Reversing with Delphi

i knew its a weird Idea to think about, i want to know if it is possible to reverse the mechanism of sorting, (i dont want to reverse the order).

for example lets say i have a random array of integers, then i sorted the array with quicksort method, now i want to go back and un-sort the array and get it back to the it was.

you may suggest i save a copy of the array, thats not what i want, think of it as a time line and have the ability to go backward or forward of sorting method.

and if it is possible please consider showing me the best way to do it with Delphi XE.

Thanks in advance.

It is not possible to unsort. You have to either:

  1. create a separate array that holds a copy of the values and then sort that array so that you can preserve the original array.

  2. create a separate array that holds pointers/indexes to the values in the original array, and then sort the second array using the values it refers to.

I usually use a function that given an array returns an array of the sorted indexes.

This way you will always have the original data and you will be able to access the data in a sorted way using something like:

for jIndex in ASortedIndexesArray do
  ShowMessage(AOriginalArray[jIndex]);

Hope this helps.

Mirko

If you want to think of it as a time line and have the ability to go backward or forward of sorting method then organize it like a timeline - with records in a file. Save each step and you will be able to reproduce it.

If the array is of integers the indices will not help you as one index (a pointer) takes the same memory as one array element. If you lack RAM use a file to store and retrieve the array. If you use larger data structures you can create, store and retrieve indices as David suggested.

You could log the swapping actions that quicksort (or whatever sorting algorithm you use) does to a list and then go forward and backward in that list to undo/redo these actions. Not simple to implement, but doable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM