2014-12-06 34 views
-4

我有一個工作的快速排序功能,但我不知道如何保留未排序數據的原始索引號。有任何想法嗎?謝謝!這是我的功能。我能否以某種方式將一對合並在一起?C++ QuickSorting矢量並保留原始索引號

double NearestNeighbor::partition(vector<double>& theList, double start, double end) { 
int pivot = theList[end]; 
int bottom = start - 1; 
int top = end; 

bool notdone = true; 
while (notdone) { 
    while (notdone) { 
     bottom += 1; 

     if (bottom == top) { 
      notdone = false; 
      break; 
     } 
     if (theList[bottom] > pivot) { 
      theList[top] = theList[bottom]; 
      break; 
     } 
    } 
    while (notdone) { 
     top = top - 1; 

     if (top == bottom) { 
      notdone = false; 
      break; 
     } 
     if (theList[top] < pivot) { 
      theList[bottom] = theList[top]; 
      break; 
     } 
    } 
} 
theList[top] = pivot; 
return top; 

}

//快速排序功能

double NearestNeighbor::quickSort(vector<double>& theList, double start, double end) { 
if (start < end) { 
    double split = partition(theList, start, end); //recursion 
    quickSort(theList, start, split - 1); 
    quickSort(theList, split + 1, end); 
} else { 
    return 0; 
} 
} 

我算過幾個向量的點積和我想打印10個最近的鄰居。我可以對它們進行排序,但是我的教授要求我們返回10個最近鄰居的索引號,所以我試圖找出如何保留這些原始索引號。

例如:分類數據可能是這個樣子:

指數:3 45 15 9 45
數據:10 14 17 30 35

我要打印出來只索引號。對不起,我無法弄清楚如何格式化數字,所以數字與數據一致,但我認爲你明白了。

+0

你應該包括更多的問題。一些代碼,以及您正在嘗試執行的示例。 – peege 2014-12-06 04:52:03

回答

1
  1. std::vector<T>轉換爲std::vector<std::pair<int, T>>
  2. 使用pair中的第二個排序std::vector<std::pair<int, T>>
+0

當我按照建議更改它時,出現以下錯誤:錯誤:無法將'__gnu_cxx :: __ alloc_traits >> :: value_type {aka std :: pair }'轉換爲'int '在初始化 ----我在這一行得到它「int pivot = theList [end];」我不知道該怎麼做...... – user3882751 2014-12-06 11:24:03

+0

@ user3882751,你必須說明'theList [end]'是'pair',而不是'int'的事實。 'int pivot = theList [end] .second;'是你需要的。 – 2014-12-07 03:13:27