fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. void merge(vector<int>&nums,int low,int mid,int high){
  5. int left= low;
  6. int right = mid+1;
  7. vector<int>temp;
  8. while(left<=mid && right<=high){
  9. if(nums[left]<=nums[right]){
  10. temp.push_back(nums[left++]);
  11. }else{
  12. temp.push_back(nums[right++]);
  13. }
  14. }
  15.  
  16. while(left<=mid){
  17. temp.push_back(nums[left++]);
  18. }
  19. while(right<=high){
  20. temp.push_back(nums[right++]);
  21. }
  22.  
  23. for(int i = low ;i <= high;i++){
  24. nums[i]= temp[i-low];
  25. }
  26. }
  27. void helper(vector<int>&nums,int low,int high){
  28. if(low>=high)return;
  29. int mid = (low+high)/2;
  30. helper(nums,low,mid);
  31. helper(nums,mid+1,high);
  32. merge(nums,low,mid,high);
  33. }
  34. vector<int>mergeSort(vector<int>&nums){
  35. int n = nums.size();
  36. helper(nums,0,n-1);
  37. return nums;
  38. }
  39. int main() {
  40. int n;cin>>n;
  41.  
  42. vector<int>a(n);
  43. for(int i = 0;i<n ;i++){
  44. cin>>a[i];
  45. }
  46.  
  47. vector<int>ans = mergeSort(a);
  48. for(int &x:ans)cout<<x<<endl;
  49. return 0;
  50. }
Success #stdin #stdout 0s 5320KB
stdin
4
1 4 3 2
stdout
1
2
3
4