Following is the Java program for Iterative Merge Sort −
Example
import java.util.Arrays; public class Demo{ public static void merge_sort(int[] my_arr){ if(my_arr == null){ return; } if(my_arr.length > 1){ int mid = my_arr.length / 2; int[] left = new int[mid]; for(int i = 0; i < mid; i++){ left[i] = my_arr[i]; } int[] right = new int[my_arr.length - mid]; for(int i = mid; i < my_arr.length; i++){ right[i - mid] = my_arr[i]; } merge_sort(left); merge_sort(right); int i = 0; int j = 0; int k = 0; while(i < left.length && j < right.length){ if(left[i] < right[j]){ my_arr[k] = left[i]; i++; } else { my_arr[k] = right[j]; j++; } k++; } while(i < left.length){ my_arr[k] = left[i]; i++; k++; } while(j < right.length){ my_arr[k] = right[j]; j++; k++; } } } public static void main(String[] args){ int my_arr[] = {56, 78, 91, 21, 34, 0, 11}; int i=0; merge_sort(my_arr); System.out.println("The array after sorting is "); for(i=0; i<my_arr.length; i++) System.out.print(my_arr[i]+" "); } }
Output
The array after sorting is 0 11 21 34 56 78 91
A class named Demo contains the ‘merge_sort’ function, that checks if the array is empty, if yes, returns nothing. If the length of the array is greater than one, the value for ‘mid’ is calculated and the array is iterated over upto the ‘mid’ value. Basically the array is divided into two equal parts and the elements to the left of the array are put into a new array and the elements to the right of the array are put into a different array. Now, these arrays are separated and sorted. Then they are merged together.
In the main function, the array is defined and the function is called on this array elements. The output is displayed on the console.