回答
使用霍爾的選擇算法(或中位數的中位數,如果你需要絕對肯定的計算複雜度),然後添加一個分區(和鴻溝由其大小來獲得平均值)。
這比排序而不是分區的顯而易見的方法快一點 - 分區是(O(N)
)其中排序是O(N log(N))
。
編輯:在C++中,對於真正的代碼(即除了家庭作業以外的任何部分需求完全由您自己完成任務),您可以使用std::nth_element
將輸入劃分爲前5等。
EDIT2:這裏還有一個快速的演示,以補充@Nils',但是這一次完全C++ 11個法衣(這麼說):
#include <numeric>
#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>
int main(){
std::vector<int> x {1, 101, 2, 102, 3, 103, 4, 104, 5, 105, 6};
auto pos = x.end() - 5;
std::nth_element(x.begin(), pos, x.end());
auto sum = std::accumulate(pos, x.end(), 0);
auto mean = sum/std::distance(pos, x.end());
std::cout << "sum = " << sum << '\n' << "mean = " << mean << "\n";
return 0;
}
排序是按升序和添加最後五個號碼
傑裏已經解釋它是如何工作的。我只是想在C添加實用的代碼示例++:
#include <algorithm>
int averageTop5 (int list[100])
{
// move top 5 elements to end of list:
std::nth_element (list, list+95, list+100);
// get average (with overflow handling)
int avg = 0;
int rem = 0;
for (int i=95; i<100; i++)
{
avg += list[i]/5;
rem += list[i]%5;
}
return avg + (rem /5);
}
隨着Jerrys的std ::積聚這就變成了一個兩班輪,但可能會失敗,整數溢出:
#include <algorithm>
#include <numeric>
int averageTop5 (int list[100])
{
std::nth_element (list, list+95, list+100);
return std::accumulate (list+95, list+100, 0)/5;
}
特別是因爲你已經有迭代器到正確的位置,我會使用'std :: accumulate'來添加數字。 – 2012-04-26 04:43:54
@jerryCoffin隨意修改代碼:-) – 2012-04-26 04:44:59
做到了..不知道std :: accumulate ..漂亮的模板。 – 2012-04-26 04:52:40
複製前5數字到數組中。確定該數組中最小元素的位置。對於列表中其餘部分的95個數字中的每一個,請將其與該最小數字進行比較。如果新號碼較大,則將其替換並重新確定短名單中新的最小號碼的位置。
最後,由5
- 1. 從數組中找出最高,最低和平均5個數字的程序
- 2. 如何找到數組中最高的三個數字?
- 3. 在輸入的10個數字中找到最高和最低
- 4. 1000個數字的字符串,找到沒有數組的最大5位數
- 5. 在Ruby中查找數組中兩個數字的總和
- 6. 找到n個大數字的總和
- 7. 找到一個數字的數字總和(在c)
- 8. 如何找到一個數組中的非相鄰數字的最大總和的數字指數
- 9. SQL - 查找表中的5個最高數字
- 10. 查找任意數字的第一個和最後一個數字的總和
- 11. 查找數組中的3個連續數字的總和
- 12. 從數組中的2個數字中找出最大和最小數字
- 13. 如何找到整數數組中的第二個最高數字?
- 14. 找到一組數組中最高總和的算法
- 15. 在matlab中查找沒有循環的下一個最高和一個數字中次數最少的數字
- 16. AS3 - 如何在數組中找到兩個最大的數字
- 17. 你如何在vb.net中找到5個最大的數字?
- 18. 最有效的方法來找到兩個數字的總和
- 19. 找到數字100中的數字總和! (我while循環不會停止)
- 20. 查找序列中下一個最高和最低的數字
- 21. 找到列中的最高數字
- 22. 找到兩個最大數字3的總和
- 23. 一個數字中連續數字的最大總和
- 24. R:得到三個數字的所有組合,總計爲100
- 25. 1000個數字的字符串,使用子串方法找到最大的5位數字,沒有數組
- 26. 如何找到數組java中最大的三個數字?
- 27. 如何找到一個數組中最大的數字
- 28. 如何找到數組中最小和最大的數字?
- 29. 從C中的數字字符串找到數字組合的總和
- 30. 如何在數組中找到最大和最小數字c
總結您的陣列和分裂這是功課? – 2012-04-26 04:20:31
不,我想開發一個特定圖形的算法,並堅持在這個代碼。 – Krishh 2012-04-26 04:22:31
3使用什麼語言 – 2012-04-26 04:24:15