给定数组范围的选择排序问题

时间:2017-07-17 03:25:25

标签: c++ sorting selection

#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循环的排序函数内开始。这个棘手的部分是函数要求数组上的边界进行选择排序,因此我很难掌握,因为我不是一个有经验的程序员。

1 个答案:

答案 0 :(得分:0)

您的程序中存在逻辑错误。您需要在每次迭代时使用当前值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;
  }
}