简体   繁体   English

C ++中的双向选择排序

[英]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? 您是说要增加i两次,一次是在for语句中,一次是在循环结束时? If you did, you really should modify your code so you're only doing it in one place. 如果这样做,您确实应该修改代码,以便只在一个地方进行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM