2017-07-17 56 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; 
    } 
}