简体   繁体   中英

Bidirectional selection sort in C++

I'm working on a program to sort a small array. This is a class assignment and required a selection sort, but I wanted to go a little further than it requested. I've done selection sorts before, and I wanted to try to implement a bidirectional version. It works, save for one problem. My second result is always the second result, and is never sorted. I feel like I'm missing something small and stupid.

Here's the code for my search function

void biSelSort(string engine[], double hits[]) {    
    int k = ARRAY_SIZE - 1;
    for (int i = 0; i < k; i++) {
        int min = i;
        int max = i;
        for (int j = i + 1; j <= k; j++) {
            if (hits[j] < hits[min]) {
                min = j;
            }
            if (hits[j] > hits[max]) {
                max = j;
            }
        }
        string tS = engine[min];
        double tD = hits[min];
        engine[min] = engine[i];
        hits[min] = hits[i];
        engine[i] = tS;
        hits[i] = tD;

        if (max == i) {
            tS = engine[min];
            tD = hits[min];
            engine[min] = engine[k];
            hits[min] = hits[k];
            engine[k] = tS;
            hits[k] = tD;
        } else {
            tS = engine[max];
            tD = hits[max];
            engine[max] = engine[k];
            hits[max] = hits[k];
            engine[k] = tS;
            hits[k] = tD;
        }
        i++;
        k--;
    }
}

Do you mean to increment i twice, once in your for statement, once at the end of your loop? If you did, you really should modify your code so you're only doing it in one place.

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