
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
C Program for Iterative Merge Sort
Merge sort what is a sorting algorithm based on the divide and conquer technique. the time complexity of merge sort is O(n log n). The algorithm first divides the array into equal halves and then merges them in a certain manner.
Iterative merge sort
In iterative merge sort, we will divide the elements into equal halves using a recursive approach and then merge them back as a sorted array using the iterative approach.
Program for iterative Merge Sort
/* Recursive C program for merge sort */
Example
#include<stdlib.h> #include<stdio.h> void merge(int arr[], int l, int m, int r) { int i, j, k; int n1 = m - l + 1; int n2 = r - m; int L[n1], R[n2]; for (i = 0; i < n1; i++) L[i] = arr[l + i]; for (j = 0; j < n2; j++) R[j] = arr[m + 1+ j]; i = 0, j = 0, k = l; while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } while (i < n1) { arr[k] = L[i]; i++; k++; } while (j < n2) { arr[k] = R[j]; j++; k++; } } void iterativeMergeSort(int arr[], int l, int r) { if (l < r){ int mid = l+(r-l)/2; iterativeMergeSort(arr, l, mid); iterativeMergeSort(arr, mid+1, r); merge(arr, l, mid, r); } } int main(){ int arr[] = {12, 11, 13, 5, 6, 7}; int size = sizeof(arr)/sizeof(arr[0]); printf("\t\t ITERATIVE MERGE SORT
"); printf("Unsorted Array : \t"); for (int i=0; i < size; i++) printf("%d ",arr[i]); iterativeMergeSort(arr, 0, size - 1); printf("
Sorted array : \t"); for (int i=0; i < size; i++) printf("%d ", arr[i]); printf("
"); return 0; }
Output
ITERATIVE MERGE SORT Unsorted Array : 12 11 13 5 6 7 Sorted array : 5 6 7 11 12 13
Advertisements