
- C Programming Tutorial
- C - Home
- C - Overview
- C - Environment Setup
- C - Program Structure
- C - Basic Syntax
- C - Data Types
- C - Variables
- C - Constants
- C - Storage Classes
- C - Operators
- C - Decision Making
- C - Loops
- C - Functions
- C - Scope Rules
- C - Arrays
- C - Pointers
- C - Strings
- C - Structures
- C - Unions
- C - Bit Fields
- C - Typedef
- C - Input & Output
- C - File I/O
- C - Preprocessors
- C - Header Files
- C - Type Casting
- C - Error Handling
- C - Recursion
- C - Variable Arguments
- C - Memory Management
- C - Command Line Arguments
- C Programming useful Resources
- C - Questions & Answers
- C - Quick Guide
- C - Useful Resources
- C - Discussion
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
- Related Articles
- Python Program for Iterative Merge Sort
- Java Program for Iterative Merge Sort
- Python Program for Iterative Quick Sort
- Java Program for Iterative Quick Sort
- Python Program for Merge Sort
- C++ Program to Implement Merge Sort
- Merge Sort for Linked Lists using C++.
- C program to sort an array by using merge sort
- Merge Sort for Doubly Linked List using C++.
- C Program for Binary Search (Recursive and Iterative)?
- Merge Sort Tree in C++
- C++ Program to Implement Merge Sort Algorithm on Linked List
- Merge Sort
- C/C++ Program to Count Inversions in an array using Merge Sort?
- 3-way Merge Sort in C++

Advertisements