-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path14.cpp
More file actions
71 lines (67 loc) · 1.55 KB
/
Copy path14.cpp
File metadata and controls
71 lines (67 loc) · 1.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
// Merge sort
// Ref: https://www.w3schools.com/dsa/dsa_algo_mergesort.php
// FFT Divide and conquer lecture - MIT
#include<iostream>
using namespace std;
void merge(int a[], int lb, int mid, int ub){
int temp[20],i,j,k;
i = lb; j = mid + 1; k = lb;
while(i<=mid && j<=ub){
if(a[i]<=a[j]){
temp[k]=a[i];
i++;
}else{
temp[k]=a[j];
j++;
}
k++;
}if(i>mid){
// Copy remaining elements from right subarray
while(j<=ub){
temp[k]=a[j];
j++; k++;
}
}else{
// Copy remaining elements from left subarray
while(i<=mid){
temp[k]=a[i];
i++; k++;
}
}
// Copy sorted temporary array back to original array
for(i=lb;i<=ub;i++){
a[i]=temp[i];
}
}
void mergesort(int a[], int lb, int ub){
if(lb<ub){
int mid = (lb+ub)/2; // Prevents potential integer overflow
mergesort(a,lb,mid);
mergesort(a,mid+1,ub);
merge(a,lb,mid,ub);
}
}
int main(){
int a[20],i,lb,ub;
cout<<"Enter the lower and upper bounds of array: ";
cin>>lb>>ub;
cout<<"Enter elements:\n";
for(i=lb;i<ub;i++){
cout<<"Element "<<i+1<<": ";
cin>>a[i];
}
cout<<"\nUnsorted Array:\n";
cout<<"[";
for(i=lb;i<ub;i++){
cout<<" "<<a[i];
}
cout<<"]\n";
mergesort(a,lb,ub);
cout<<"\nSorted Array:\n";
cout<<"[";
for(i=lb;i<ub;i++){
cout<<" "<<a[i];
}
cout<<"]\n";
return 0;
}