GeeksforGeeks » Algorithms
In-place Merge Sort
(5 posts)-
As the title says, the goal of this Question is go perform an In-place(Without any extra memory or O(1) constant extra memory) merge sort of numbers in Array Implementation.
Inspiration :
There is a rack in which wine bottles are present with different concentration of wines in a random order. Our goal is to make sure we arrange all the Wine bottles in an either increasing order or decreasing order of conc. WITHOUT using any extra bottles or any extra space ! ( i.e the bottles can just be shuffled with hand in the rack)
-
#include<stdlib.h> #include<stdio.h> void swap(int *a, int *b) { int temp = *a; *a = *b; *b = temp; } void merge(int arr[], int l, int m, int r) { int i, j, k; int n1 = m - l + 1; int n2 = r - m; i = 0; j = 0; k = l; while (i<n1 && j<n2) { if (arr[l+i] <= arr[m+1+j]) { swap(&arr[l+i], &arr[k]); i++; } else { swap(&arr[m+1+j], &arr[k]); j++; } k++; } } /* l is for left index and r is right index of the sub-array of arr ot be sorted */ void mergeSort(int arr[], int l, int r) { if(l < r) { int m = r-l-1; mergeSort(arr, l, m); mergeSort(arr, m+1, r); merge(arr, l, m, r); } } void printArray(int A[], int size) { int i; for(i=0; i < size; i++) printf("%d ", A[i]); printf("\n"); } int main() { int arr[] = {10, 11, 5, 6}; int n = sizeof(arr)/sizeof(arr[0]); mergeSort(arr, 0, n-1); printArray(arr, n); getchar(); return 0; } -
Instead of dividing the array in two halves, I haved divided the array in two arrays: one contain n-1 elements, other contains 1 element. The worst case time complexity will be O(n^2)
-
Merge Sort Worst Time Analysis is supposed to be O(nlogn)
So, If time goes to O(n^2) , There are better in place sorting algorithms that can do it nah ? Like Bubble Sort and Insertion Sort ?
Reply
You must log in to post.