fork download
  1. #include <iostream>
  2. #include <unordered_map>
  3. #include <vector>
  4. #include <algorithm>
  5.  
  6. using namespace std;
  7.  
  8. // Function to group elements of the given array based on first occurrence
  9. // of each element
  10. void rearrange(int A[], int n)
  11. {
  12. // create an empty map to store frequency of each element
  13. // present in the input array
  14. unordered_map<int, int> freq;
  15. vector<int> order;
  16.  
  17. // traverse the input array and update frequency of each element
  18. for (int i = 0; i < n; i++) {
  19. freq[A[i]]++;
  20.  
  21. if (std::find(order.begin(), order.end(), A[i]) == order.end())
  22. {
  23. order.push_back(A[i]);
  24. }
  25. }
  26.  
  27. for (auto & nb : order)
  28. {
  29. for (int i = 0;i < freq[nb];i++)
  30. {
  31. cout << nb << " ";
  32. }
  33. }
  34. }
  35.  
  36. // main function
  37. int main()
  38. {
  39. int A[] = { 5, 4, 5, 5, 3, 1, 2, 2, 4 };
  40. int n = sizeof(A)/sizeof(A[0]);
  41.  
  42. rearrange(A, n);
  43.  
  44. return 0;
  45. }
  46.  
Success #stdin #stdout 0s 4280KB
stdin
Standard input is empty
stdout
5 5 5 4 4 3 1 2 2