Search code examples
algorithmsortingpseudocode

Pseudocode of sorting a list of strings without using loops


I was trying to think of an algorithm that would sort a list of strings according to its first 4 chars (say each line from a file), without using the conventional looping methods such as while,for. An example of inputs would be:

1231COME1900123
1233COME1902030
2031COME1923919
1231GO 1231203
1233GO 1932911
2031GO 1239391

The thing is, we do not know the number of records there can be beforehand. And each 4-digit ID number can have multiple COME and GO records. But they are sorted as above beforehand. And I want to sort the file by their 4-digit ID number. And achieve this:

1231COME1900123
1231GO 1231203
1233COME1902030
1233GO 1932911
2031COME1923919
2031GO 1239391

The only logical comment I can have is that we should be using a recursive way to read through the records, but the sorting part is a bit tricky for me. Also GOTO could be used as well. Any ideas?


Solution

  • Assuming that the 1st 4 characters of each entry are always digits, you do something as follows:

    1. Create a list of length 10000, where each element can hold a pair of values.
    2. Enter into that element of the list based upon the first 4 digits.
    3. The shape of the individual elements will be as follows -> [COME_ELEMENT, GO_ELEMENT].
    4. Each COME_ELEMENT and GO_ELEMENT is a list in itself, of length equal to the maximum value + 1 that can appear after the words COME & GO.
    5. Now, as the string arrives break it at the 1st 4 digits. Now, go to that element of the list.
    6. After that, check whether it's a go or come.
    7. If it's a go (suppose), then determine the number after the word go.
    8. Insert the string at the index (determined in 7th step) in the inner list.
    9. When you're done with inserting values, just traverse the non-empty elements.

    The result so obtained will contain the sorted order that you require without the use of looping.