fork download
  1. #include <iostream>
  2. #include <vector>
  3.  
  4. int main() {
  5. int unsorted[] = {5,7,12,890,-5,-4,3,2,1,56,890,-1043};
  6. std::vector<bool> tracker(12, false);
  7. const int n = 5; //we want the top n largest numbers
  8. std::vector<int> topN;
  9.  
  10. for(int i = 0; i < n; i++) {
  11. //an integer needs to store the maximum in the list.
  12. //but it cannot be one that has already been marked
  13. //as true in tracker.
  14. //so first we will loop until the first un-marked number.
  15. int unmarked_index = 0;
  16. for(; unmarked_index < tracker.size(); unmarked_index++) {
  17. if(!tracker[unmarked_index]) {
  18. //we found one that has not been visited yet
  19. break;
  20. }
  21. }
  22. //the max variable will hold the maximum after the next
  23. //loop finishes. first we must initialize it
  24. //and the loop we just came from gives us the
  25. //index to initialize with.
  26. //also, we must keep track of where the max is found
  27. //so that it can be marked in tracker after the loop
  28. int max = unsorted[unmarked_index];
  29. int max_index = unmarked_index;
  30. for(int j = unmarked_index+1; j < tracker.size(); j++) {
  31. if(!tracker[j] && unsorted[j] > max) {
  32. //if j is not marked and j is > max
  33. max = unsorted[j];
  34. max_index = j;
  35. }
  36. }
  37. //time to mark max as used
  38. tracker[max_index] = true;
  39. //and add max to topN
  40. topN.push_back(max);
  41. }
  42.  
  43. for(int i = 0; i < topN.size(); i++) {
  44. std::cout << topN[i];
  45. if(i != topN.size() - 1) std::cout << ", ";
  46. }
  47. std::cout << std::endl;
  48.  
  49. return 0;
  50. }
Success #stdin #stdout 0s 3228KB
stdin
Standard input is empty
stdout
890, 890, 56, 12, 7