【问题标题】:Selection sort issue given array range给定数组范围的选择排序问题
【发布时间】:2017-12-21 11:26:56
【问题描述】:
#include <iostream>
using namespace std;
// copy the swap function of lab10a
// copy the smallest function of lab10b
int sorting(int a[], int left, int right) {
    // parameter a[] is the array to be sorted
    // parameter left is the left index
    // parameter right is the right index
    // the function returns the index i, where a[i] is the
    // smallest value in a[left..right]
    // if (left > right || left < 0 || right < 0)
    //error cases and return 1 for failure
    // use a loop to iterate each index from left to right
    // and let i be the variable in the iteration
    // interchange the values of a[i] and a[ smallest(a, i, right) ]
    if (left > right || left < 0 || right < 0) {
        cout << "Error index out of bounds" << endl;
        return -1;
    }
    int temp;
    int index = left;
    for (int i = index; i <= right; i++) {
        int j = i;
        while (j <= right) {
            if (a[j] < a[index])
                index = j;
            j++;
        }
        temp = a[index];
        a[index] = a[i];
        a[i] = temp;
    }
    return 0; //for success
}
// Program to test sorting function
//-----------------------------------------
int main()
{
    int a[] = {9,1,5,7,4,2,6,0,8,3};

    // test case one
    sorting(a, 1, 5);
    cout << " The value in A[1..5] is sorted nondecreasingly\n";
    for (int i = 0; i<10; i++)
        cout << "a[" << i << "] = " << a[i] << endl;
    // test case two
    sorting(a, 0, 9);
    cout << " The value in A[0..9] is sorted nondecreasingly\n";
    for (int i = 0; i<10; i++)
        cout << "a[" << i << "] = " << a[i] << endl;

    return 0;
}

我在使用这种排序算法时遇到了问题。当我运行它时,它的工作似乎很奇怪,我似乎无法确定问题出在哪里。我知道问题所在的部分从第一个 for 循环的排序函数开始。棘手的部分是该函数要求数组上的边界来进行选择排序,因此由于我不是经验丰富的程序员,因此很难掌握。

【问题讨论】:

  • 在调试器中逐步完成排序循环。您应该能够发现问题。

标签: c++ sorting selection


【解决方案1】:

您的程序中存在逻辑错误。您需要在每次迭代时使用 i 的当前值更新索引。

试试这个,效果很好:

int temp;
int index ;
for (int i = left; i <= right; i++) {
    index =i;
    int j = i+1;
    while (j <= right) {
        if (a[j] < a[index])
            index = j;
        j++;
    }
    if(index != i){
    temp = a[i];
    a[i] = a[index];
    a[index] = temp;
  }
}

【讨论】:

    猜你喜欢
    • 2011-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-18
    • 1970-01-01
    • 2015-01-17
    • 1970-01-01
    相关资源
    最近更新 更多