Merge sort algorithm in java with example program

  • Merge sort one of the recursive sorting algorithm.
  • First divide the list of unsorted elements in two two parts. left half and right half.

  • Divide the left part elements in to sub lists until it become single element.
  • Divide right half of array or list of elements in to sub lists until it becomes one element in list.
  • After dividing all elements in two parts in to single entity. 
  • Merge the elements into two by comparing lesser element will be first. apply same at right half
  • Merge all the elements in the left part until it become single sorted list
  • Now we have two sorted parts.
  • Means two parts sorted in ascending order and smaller element will be in first position.
  • Compare fist elements of two parts , lesser one should be takes first place in new sorted list
  • New sorted list or array having only one element now.
  • Compare two lists elements and place in sorting order and merge it. 
  • Finally we have all elements sorted.
  • Compared to remaining algorithms like selection sort, insertion sort and bubble sort  merge sort works faster.
  • Lets see what will be the time complexity of merge sort algorithm.

Time complexity of merge sort algorithm:


1.Best case  time complexity:      O(n log (n))
2.Average case time complexity: O(n log (n))
3.Worst case time complexity:    O(n log (n))
4.Worst case space complexity:  O(n)


Merge sort in java with explanation diagram

Implement merge sort in java


Program#1: Java program to implement merge sort algorithm data structure

  1. package com.instanceofjava.mergesortalgorithm;

  2. public class MergeSortAlgorithm {

  3.    private int[] resarray;
  4.    private int[] tempMergArray;
  5.    private int length;
  6.  
  7.  public static void main(String a[]){
  8.         
  9.  int[] inputArr ={6,42,2,32,15,8,23,4};
  10.         System.out.println("Before sorting");

  11.        for(int i:inputArr){
  12.           System.out.print(i);
  13.            System.out.print(" ");
  14. }

  15.  MergeSortAlgorithm mergesortalg = new MergeSortAlgorithm();

  16.        mergesortalg.sort(inputArr);
  17.        System.out.println();

  18.        System.out.println("After sorting");
  19.        for(int i:inputArr){
  20.            System.out.print(i);
  21.            System.out.print(" ");
  22.        }
  23.  }
  24.     
  25. public void sort(int inputArray[]) {

  26.        this.resarray = inputArray;
  27.        this.length = inputArray.length;
  28.        this.tempMergArray = new int[length];
  29.        doMergeSort(0, length - 1);

  30. }
  31.  
  32. private void doMergeSort(int lowerIndex, int higherIndex) {
  33.         
  34.     if (lowerIndex < higherIndex) {

  35.    int middle = lowerIndex + (higherIndex - lowerIndex) / 2;

  36.            //to sort left half of the array
  37.    doMergeSort(lowerIndex, middle);

  38.            // to sort right half of the array
  39.    doMergeSort(middle + 1, higherIndex);

  40.            //merge two halfs
  41.     mergehalfs(lowerIndex, middle, higherIndex);
  42. }
  43. }
  44.  
  45. private void mergehalfs(int lowerIndex, int middle, int higherIndex) {
  46.  
  47.        for (int i = lowerIndex; i <= higherIndex; i++) {
  48.         tempMergArray[i] = resarray[i];
  49.        }

  50.        int i = lowerIndex;
  51.        int j = middle + 1;
  52.        int k = lowerIndex;

  53.   while (i <= middle && j <= higherIndex) {
  54.            if (tempMergArray[i] <= tempMergArray[j]) {
  55.             resarray[k] = tempMergArray[i];
  56.                i++;
  57.            } else {
  58.             resarray[k] = tempMergArray[j];
  59.                j++;
  60.            }
  61.            k++;
  62.       }

  63.      while (i <= middle) {
  64.         resarray[k] = tempMergArray[i];
  65.            k++;
  66.            i++;
  67.        }
  68.    }

  69. }

Output:

  1. Before sorting
  2. 6  42  2  32  15  8  23  4
  3. After sorting
  4. 2  4  6  8  15  23  32  42 

Insertion sort algorithm in java programming

  • Sorting means arranging elements of a array or list in ascending or descending order.
  • We have various sorting algorithms in java.

  • Iterative and recursive algorithms.
  • Insertion sort is iterative type of algorithm.
  • Insertion sort algorithm is in place algorithm
  • The basic idea behind insertion sort is to divide our list in to two parts , sorted and un sorted.
  • At each step of algorithm a number is moved from un sorted part to sorted part.
  • Initially take 1st element as sorted element. 
  • Noe take second element and compare with first element if it less than the 1st element then swap two numbers means place lesser value in first position.
  • So now have two elements in sorted part. Take third element and compare with second element if it is less than the second element then we need to compare it with 1st element if is less than first element we need keep that in first place. Take an element  from unsorted portion and compare with sorted portion and place it in correct position in order to make sorted.
  • This will be repeated until entire list will be sorted.

Time complexity of Insertion sort:

1.Best case  time complexity:      O(n2)
2.Average case time complexity: O(n2)
3.Worst case time complexity:     O (n2)
4.Worst case space complexity:  O(1)


Implementation of Insertion sort algorithm in java

Implement insertion sort in java


Program #1: Write a java example program on insertion sort algorithm.

  1. package com.instanceofjava.insertionsortalgorithm;

  2. public class InsertionSort {

  3. /**
  4. * @website: www.instanceofjava.com
  5. * @category: insertion sort algorithm in java
  6. */
  7.      
  8. public static int[] doInsertionSort(int[] array){
  9.          
  10.      int temp;
  11.  
  12.   for (int i = 1; i < array.length; i++) {
  13.  
  14.             for(int j = i ; j > 0 ; j--){
  15.                 if(array[j] < array[j-1]){
  16.                     temp = array[j];
  17.                     array[j] = array[j-1];
  18.                     array[j-1] = temp;
  19.                 }
  20.             }
  21.  
  22.        }
  23.         return array;
  24.  }
  25.  
  26.   static void printArray(int[] inputarray){
  27.  
  28.     for(int i:inputarray){
  29.              System.out.print(i);
  30.              System.out.print(", ");
  31.          }
  32.     System.out.println();
  33.   }
  34.     
  35.  public static void main(String a[]){
  36.    
  37.    int[] array = {16,12,3,11,9,21,5,6};
  38.  
  39.     System.out.println("Before sorting elements");
  40.     printArray(array);
  41.  
  42.     int[] resarray = doInsertionSort(array);
  43.  
  44.     System.out.println("After sorting elements");
  45.     printArray(array);
  46.        
  47. }
  48. }

Output:

  1. Before sorting elements
  2. 16, 12, 3, 11, 9, 21, 5, 6, 
  3. After sorting elements
  4. 3, 5, 6, 9, 11, 12, 16, 21,

Implementation of selection sort algorithm in java with Example program

  • Selection sort algorithm is to arrange unsorted elements in to sorting order with increasing or decreasing order.
  • To sort list of  unsorted list of elements first it will search for minimum value in the list and place it in first index.

  • Now first place is fixed with smallest value in the list now it starts from second element and compare next element and if it is big it compares next element if it is small it picks that element and compares with next element.
  • So again it picks smallest element in the list and place it in second place. This procedure will repeat until it reaches n-1 position.

Time complexity of selection sort algorithm: 


1.Best case  time complexity:     O(n2)
2.Average case time complexity: O (n2)
3.Worst case time complexity:     O (n2)


Program #1:  Write a  Java example program to sort unsorted elements in ascending order using selection sort algorithm

  1. package com.java.sortingalgorithms;

  2. public class SelectionSortInJava {

  3. public static int[] selectionSortArray(int[] array){
  4.         
  5. for (int i = 0; i < array.length - 1; i++)
  6. {
  7.            int index = i;

  8.   for (int j = i + 1; j < array.length; j++)

  9.                if (array[j] < array[index])
  10.                    index = j;
  11.      
  12.            int minimumNumber = array[index]; 
  13.            array[index] = array[i];
  14.            array[i] = minimumNumber;

  15. }
  16.        return array;
  17.  }
  18.      
  19. public static void main(String a[]){
  20.          
  21.  int[] array = {12,24,6,56,3,9,15,41};
  22.         
  23.    System.out.println("Before sorting");
  24.        
  25.     for(int i:array){
  26.   System.out.print(i);
  27.   System.out.print(", ");
  28.    }
  29.  
  30.    int[] resultarr = selectionSortArray(array);
  31.        
  32.        System.out.println("\nAfter sorting"); 

  33.       for(int i:resultarr){

  34.     System.out.print(i);
  35.     System.out.print(", ");
  36.      }
  37. }
  38. }

Output:

  1. Before sorting
  2. 12, 24, 6, 56, 3, 9, 15, 41, 
  3. After sorting
  4. 3, 6, 9, 12, 15, 24, 41, 56,

Implementation of Selection Sort algorithm

selection sort in java example program

Quicksort algorithm in java with example program

  • Quick sort uses divide and conquer algorithm.
  • First will be divided in to two parts based on some pivot element. All elements which are less than pivot element will be placed left and and all elements which are greater than pivot will be in right part.

  • So now pivot element is exactly in middle. if we sort left and right side elements all elements will be sorted. Here recursive quick sort will take place in order to sort all elements.
  • Quick sort will be sorting these elements without using extra space that is the reason it is called in place sorting algorithm.
  • Using the first or middle elements as an pivot element. it splits the arrays by re arranging the elements like every thing that is less than pivot will come left side and all elements greater than or equal to pivot will come right side.
  • Now pivot is in middle and correct place it left and right arrays sorted then entire array will be sorted.
  • Quick sort exactly will do the same it will sort left and right recursively.
  • If size of input is very  less merge sort will be time consuming.
  • For smaller inputs quick sort is faster than merge sort.
  • Time complexity of Quicksort  default case is O(n log n).
  • Worst case Time complexity of  Quicksort  is O(n2).
Steps to implement quick sort algorithm: 

  • Create a array with some elements. Choose pivot element as middle element. we can choose first or last also.
  • After choosing pivot element arrange the elements like all elements which are less than pivot value comes left side and elements greater than equal to pivot come right side of pivot.
  • And then apply same to both sides. until it becomes one. then all elements in array will be sorted.

 Program #1: Java Example program to sort elements of array using quick sort algorithm:

  1. package quicksortjava;

  2. public class QuickSort {
  3.  
  4.     private int array[];
  5.     private int length;
  6.  
  7. public void sortElements(int[] arrayvalues) {
  8.          
  9.         if (arrayvalues == null || arrayvalues.length == 0) {
  10.             return;
  11.         }
  12.         this.array = arrayvalues;
  13.         length = arrayvalues.length;
  14.         doQuickSort(0, length - 1);
  15. }
  16.  
  17.   private void doQuickSort(int lowIndex, int highIndex) {
  18.          
  19.         int i = lowIndex;
  20.         int j = highIndex;
  21.         
  22.         int pivot = array[lowIndex+(highIndex-lowIndex)/2];
  23.         
  24.         // now Divide the array into two arrays(actually we are maintaining single array only)
  25.         while (i <= j) {
  26.        
  27.             while (array[i] < pivot) {
  28.                 i++;
  29.                 
  30.             }
  31.             while (array[j] > pivot) {
  32.                 j--;
  33.             }
  34.             if (i <= j) {
  35.                 swapElements(i, j);
  36.                
  37.                 //move index to next position on both sides
  38.                
  39.                 i++;
  40.                 j--;
  41.                 
  42.                 
  43.             }
  44.         }
  45.         
  46.         // call quickSort() method recursively
  47.         if (lowIndex < j){
  48.        
  49.         doQuickSort(lowIndex, j);
  50.         }
  51.         if (i < highIndex){
  52.        
  53.         doQuickSort(i, highIndex);
  54.             
  55.         }
  56.     }
  57.  
  58.     
  59.      
  60. private void swapElements(int i, int j) {

  61.         int temp = array[i];
  62.         array[i] = array[j];
  63.         array[j] = temp;

  64.  }
  65.      
  66.  public static void main(String a[]){
  67.          
  68.     QuickSort quicksort = new QuickSort();
  69.         int[] inputarray = {32,1,23,14,43,7,6,65};
  70.         
  71.         System.out.println("Before sorting");
  72.         for(int i:inputarray){
  73.             System.out.print(i);
  74.             System.out.print(" ");
  75.         }
  76.        
  77.  quicksort.sortElements(inputarray);

  78.         System.out.println("After sorting");
  79.         for(int i:inputarray){
  80.             System.out.print(i);
  81.             System.out.print(" ");
  82.         }
  83.     }

  84. }
 Output:

  1. Before sorting
  2. 32 1 23 14 43 7 6 65 
  3. After sorting
  4. 1 6 7 14 23 32 43 65 

Execution flow explanation of quick sort algorithm

quick sort program in java using recursion program

Select Menu