简体   繁体   中英

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?

It seems there is a typo in the function declaration

void selsort(media mry[], int n)
             ^^^^^

I think you mean

void selsort( Data mry[], int n)
              ^^^^

This if statement

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

does not make sense.

You should write

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

Or if you want to sort in the ascending order then write the condition like

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

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.

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