Search code examples
c++classsortingselection-sort

selection sort for array of objects


Iam trying to make selection sort for array of objects considering i have Data class

I want to sort them depending on the id attribute of the object

class Data
{
public:
    string name;
    int id;
};

    }
int main()
{
    Data m[3];
    m[0].id = 5;
    m[1].id = 4;
    m[2].id = 8;
    selsort(m, 3);
    cout << m[0].id;
};

I cannot understand what is wrong nothing happens to the array ?


Solution

  • Change:

    if ((mry[min].id < mry[j].id) < 0)
    

    to:

    if ((mry[min].id > mry[j].id) )
    

    You are finding the minimum index, so you have to swap if you find an index with a value that is lesser than the current minimum.

    A better way to accomplish this is to make your function take in another parameter called a comparator function which tells the function how to compare; that way you can reuse your function if you change to mind and what to sort it by another parameter.

    void selsort(Data mry[], int n, std::function<int(Data, Data)> cmp) // mry[] is the object array, n is the 
                                         // number of objects in the array
        {
            int pass, j, min;
            Data temp;
            for (pass = 0; pass <= n - 2; pass++)  // passes
            {
                min = pass;
                for (j = pass + 1; j < n; j++)  // in each pass
                    if (cmp(mry[min], mry[j]) > 0)
                        min = j;
                temp = mry[min];
                mry[min] = mry[pass];
                mry[pass] = temp;
            }
    
        }
    

    And you can define a compare by id function:

    int compare_by_id(Data d1, Data d2) 
    {
        return d1.id - d2.id;
    }
    

    Call your function like this:

    selsort(array, size, compare_by_id);
    

    The best part is you can define your own function that can compare the elements as you want and that way your selsort() is versatile.