2017-05-04 25 views
-1

我想要做的是實現一個簡單的選擇排序算法,該算法使用函數minButGreaterThan來查找數組中的下一個最小數字。我的問題是,如果數組有一個重複的號碼,它會被傳遞並留在最後。我試着改變控制if語句來適應這個,但似乎沒有任何工作。有什麼建議?選擇排序不會捕獲重複的數字

double GradeBook::minButGreaterThan(double x) // - NEEDS TESTING 
    { 
     double minButGreaterThan = -1; 
     for (int i = 0; i < classSize; i++) 
     { 
      if (grades[i] > x) 
      { 
       minButGreaterThan = grades[i]; 
       break; 
      } 
     } 
     for (int i = 0; i < classSize; i++) 
     { 
      if (grades[i] > x && grades[i] <= minButGreaterThan) 
       minButGreaterThan = grades[i]; 
     } 

     return minButGreaterThan; 
    } 

void GradeBook::selectionSort() //ascending order -- *DOES NOT WORK WITH DUPLICATE SCORES* - RETEST 
{ 
    double min = absoluteMin(); 
    for (int i = 0; i < classSize; i++) 
    { 
     if (grades[i] == min) 
     { 
      double temp = grades[0]; 
      grades[0] = grades[i]; 
      grades[i] = temp; 
      break; 
     } 
    } 

    for (int i = 0; i < classSize-1; i++) 
    { 
     double next = minButGreaterThan(grades[i]); 
     for (int n = 1; n <= classSize; n++) 
      if (grades[n] == next) 
      { 
       double temp = grades[n]; 
       grades[n] = grades[i+1]; 
       grades[i+1] = temp; 
      } 
    } 

} 
+0

這可能適合codereview.stackexchange.com –

回答

0

應該使用重複項,選擇排序只需將最小值移動到左邊,然後移動到數組的「排序」部分。

這是我實現:

#include <algorithm> 
#include <vector> 

using std::swap; 
using std::vector; 
using std::min_element; 

void selectionSort(vector<int> &v) { 
    for (unsigned int i = 0; i < v.size() - 1; i++) { 
     auto minElement = min_element(v.begin() + i, v.end()); 
     auto minIndex = minElement - v.begin(); 
     swap(v[i], v[minIndex]); 
    } 
} 

您可能需要修改它與花車工作。現在,雙浮動精度等級(double)似乎太多了。我認爲經常float是好的。

+0

需要它使用給定的函數minButGreaterThan但感謝您的無用輸入,我猜...? –