fork download
  1. #include <iostream>
  2. using namespace std;
  3. void Sort_Ascending(int arr[],int l,int r,int mid) {
  4. int i=l,j=mid+1,k=l,temp[r+1];
  5. while (i<=mid and j<=r) {
  6. if (arr[i]<arr[j]) {
  7. temp[k++]=arr[i++];
  8. }
  9. else temp[k++]=arr[j++];
  10. }
  11. while (i<=mid)temp[k++]=arr[i++];
  12. while (j<=r) temp[k++]=arr[j++];
  13. for (int i=l;i<=r;i++)arr[i]=temp[i];
  14. }
  15. void Sort_Descending(int arr[],int l,int r,int mid) {
  16. int i=l,j=mid+1,k=l,temp[r+1];
  17. while (i<=mid and j<=r) {
  18. if (arr[i]>arr[j]) {
  19. temp[k++]=arr[i++];
  20. }
  21. else temp[k++]=arr[j++];
  22. }
  23. while (i<=mid)temp[k++]=arr[i++];
  24. while (j<=r) temp[k++]=arr[j++];
  25. for (int i=l;i<=r;i++)arr[i]=temp[i];
  26. }
  27. void merge(int arr[],int l, int r, bool ascending) {
  28. if (r>l) {
  29. int mid=(l+r)/2;
  30. merge(arr,l,mid,ascending);
  31. merge(arr,mid+1,r,ascending);
  32. if (ascending)Sort_Ascending(arr,l,r,mid);
  33. else Sort_Descending(arr,l,r,mid);
  34. }
  35. }
  36. int main() {
  37. // Time Complexity = nlog(n)
  38.  
  39. int a1[]={4,1,6,2,7,3};
  40. int n1=sizeof(a1) / sizeof(a1[0]);
  41. cout<<"Before Ascending Sort: ";
  42. for (int i=0;i<n1;i++)cout<<a1[i]<<" ";
  43. cout<<"\n";
  44. merge(a1, 0, n1 - 1, true);
  45. cout << "After Ascending Sort: ";
  46. for (int i=0;i<n1;i++)cout<<a1[i]<<" ";
  47. cout<<"\n";
  48.  
  49. int a2[]={10,2,8,5, 3, 9};
  50. int n2=sizeof(a2)/ sizeof(a2[0]);
  51. cout<<"\nBefore Descending Sort: ";
  52. for (int i=0;i<n2;i++)cout<<a2[i]<<" ";
  53. cout<<"\n";
  54. merge(a2,0,n2-1,false);
  55. cout << "After Descending Sort: ";
  56. for (int i=0;i<n2;i++)cout<<a2[i]<<" ";
  57. cout<<"\n";
  58. return 0;
  59. }
Success #stdin #stdout 0.01s 5288KB
stdin
Standard input is empty
stdout
Before Ascending Sort: 4 1 6 2 7 3 
After Ascending Sort:  1 2 3 4 6 7 

Before Descending Sort: 10 2 8 5 3 9 
After Descending Sort:  10 9 8 5 3 2