简体   繁体   中英

Bubble Sort 2D Array

I have a 2D array that looks like this;

0. PID: 0, PRI:-1
1. PID: 0, PRI:-1
2. PID: 0, PRI:-1
3. PID: 15, PRI:4
4. PID: 209, PRI:5
5. PID: 0, PRI:0
6. PID: 0, PRI:0
7. PID: 0, PRI:0
8. PID: 0, PRI:0
9. PID: 0, PRI:0

What is the fastest and most logical way to move the PID's with valid PRI's (where PRI > 0) to the top of the array, whilst keeping them in numerical order based on the PRI.

Thanks

At least from your description, you only care about sorting on PRI values, but want the negative values to come after positive ones (but the positive ones to be in order).

One easy way to do this is to cast the PRI values to unsigned before doing the comparison. When converted to unsigned, a negative value will be reduced modulo 2 N -1 so (for example) -1 will convert to UINT_MAX (and, more importantly, all negative numbers will convert to unsigned numbers greater than anything that started out as a positive signed number).

typedef struct { 
    int PID;
    int PRI;
} proc;

int cmp(void const *a, void const *b) { 
    proc const *aa = (proc const *)a;
    proc const *bb = (proc const *)b;

    if ((unsigned)(bb->PRI) < (unsigned)(aa->PRI))
        return -1;
    if ((unsigned)(aa->PRI) < (unsigned)(bb->PRI))
        return 1;
    return 0;
}

At the end, instead of returning 0 based only on equality of the PRI values, you may also want to add a comparison of the PIDs, so items will equal PRI values will be sorted by PID. I've left that out for now, since you haven't said that you really need/want it (and it makes the code a bit longer and potentially harder to understand, especially if you're not expecting it to be there).

Edit: In case it wasn't clear, this comparison function is intended to work with qsort , and (assuming you do the comparison correctly) a stable sort isn't necessary. You only need a stable sort if you decided go the (nearly always slower) route of sorting first on one field, then doing a second (separate) sort on a second field, rather than comparing on all the relevant fields in a single comparison.

You can sort the array on PRI in descending order. Or instead of using -1, you can define invalid PRI like this:

const int INVALID_PRI = INT_MAX;

And sort the array on the PRI column.

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