2017-07-17 12 views
-1
#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ループのソート関数内で始まります。このトリッキーな部分は、関数が選択ソートを行うために配列の境界を要求するため、私は経験豊富なプログラマーではないので把握が難しくなっています。選択ソート問題の配列範囲

+0

ステップデバッガでのソートのループスルー。あなたは問題を見つけることができるはずです。 – 1201ProgramAlarm

答えて

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; 
    } 
}