Search code examples
arrayssortingpseudocode

How can I sort an array that is already sorted by a secondary criteria?


Suppose I have an array of objects. Each object contains and integer and a string.

These objects have been sorted so that they are in alphabetical order, and no two objects contain the same string.

I want to sort the array so that they are in order from lowest to highest integer, and for objects with the same integer I want to sort tem in alphabetical order

For example I start with:

[1 "ab"],[2 "bc"],[1 "cd"],[3 "de"],[2 "ef"]

and it should be sorted to:

[1 "ab"],[1 "cd"],[2 "bc"],[2 "ef"],[3 "de"]

Is there a faster way than just sorting with language built in comparator sort functions? (where I provide a comparison function)


Solution

  • There could be, but
    I think comparison function is much better than anything

    bool comp(obj a, obj b)
    {
        if(a.num==b.num)return a.str < b.str;
        return a.num<b.num;
    }
    

    call to comp function sort(arr, arr+size, comp)