merge sort
merge sort
1. Divide: Divide the list or array recursively into two halves until it can
no more be divided.
algorithm.
order. The process continues until all elements from both subarrays
#include<iostream.h>
#include<conio.h>
class sort{
public:
void merge(int a[],int low,int mid,int high){
int tmp[5];
int i=low;
int k=low;
int j=mid+1;
while((i<=mid)&&(j<=high)){
if(a[i]<=a[j]){
tmp[k]=a[i];
i++;
}
else{
tmp[k]=a[j];
j++;
}
k++;
}
while(i<=mid){
tmp[k]=a[i];
k++;
i++;
}
while(j<=high){
tmp[k]=a[j];
k++;
j++;
}
for(i=low;i<=high;i++){
a[i]=tmp[i];
}
}
**Overview**:
1. **Initialization**:
- Start with an array `a[]` that needs to be sorted.
- Call the function `merge_sort(a, 0, n-1)` where `n` is the length of array.
2. **Recursive Splitting**:
- In the `merge_sort` function:
- If `low` is not equal to `high`:
- Calculate `mid` as the middle index of the array section (`mid = (low
+ high) / 2`).
- Recursively call `merge_sort` on the left half (`a[low]` to `a[mid]`).
- Recursively call `merge_sort` on the right half (`a[mid+1]` to
`a[high]`).
3. **Merging**:
- Once both halves have been recursively split down to single elements,
start merging them back together:
- Call `merge(a, low, mid, high)` to merge the two sorted halves.
- Inside the `merge` function:
- Create a temporary array `tmp[]` to hold the merged result.
- Initialize pointers `i` to `low` and `j` to `mid + 1` to point to the start
of the left and right halves, respectively.
- Compare the current elements pointed by `i` and `j`. Place the
smaller element into the temporary array and advance the pointer.
- Repeat this process until you reach the end of one of the halves.
- Copy any remaining elements from the left half into `tmp[]`.
- Copy any remaining elements from the right half into `tmp[]`.
- Once all elements are merged, copy the merged temporary array
back into the original array `a[]` from `low` to `high`.
4. **Repeat**:
- Continue the process of recursive splitting and merging until the entire
array is sorted.