Paste Search Dynamic
Recent pastes
swapping
  1. #include<iostream>
  2. using namespace std;
  3. void swapping(int &a, int &b) {
  4. int temp;
  5. temp = a;
  6. a = b;
  7. b = temp; }
  8. void display(int *array, int size) {
  9. for(int i = 0; i<size; i++)
  10. cout << array[i] << " ";
  11. cout << endl; }
  12. void merge(int *array, int l, int m, int r) {
  13. int i, j, k, nl, nr;
  14. nl = m-l+1;
  15. nr = r-m;
  16. int larr[nl], rarr[nr];
  17. for(i = 0; i<nl; i++)
  18. larr[i] = array[l+i];
  19. for(j = 0; j<nr; j++)
  20. rarr[j] = array[m+1+j];
  21. i = 0; j = 0; k = l;
  22. while(i < nl && j<nr) {
  23. if(larr[i] <= rarr[j]) {
  24. array[k] = larr[i];
  25. i++;
  26. }
  27. else{
  28. array[k] = rarr[j];
  29. j++;
  30. }
  31. k++;
  32. } while(i<nl)
  33. {
  34. array[k] = larr[i];
  35. i++;
  36. k++; }
  37. while(j<nr) {
  38. array[k] = rarr[j];
  39. j++; k++; } }
  40. void mergeSort(int *array, int l, int r) {
  41. int m;
  42. if(l < r) {
  43. int m = l+(r-l)/2;
  44. mergeSort(array, l, m);
  45. mergeSort(array, m+1, r);
  46. merge(array, l, m, r); } }
  47. int main() {
  48. int n;
  49. cout << "Enter the number of elements: ";
  50. cin >> n;
  51. int arr[n];
  52. cout << "Enter elements:" << endl;
  53. for(int i = 0; i<n; i++) {
  54. cin >> arr[i]; }
  55. cout << "Array before Sorting: ";
  56. display(arr, n);
  57. mergeSort(arr, 0, n-1);
  58. cout << "Array after Sorting: ";
  59. display(arr, n); }
  60.  
Parsed in 0.005 seconds