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 

How to use Javascript confirm dialogue box

  • Confirm dialogue box in java script used to display a message for an action weather its is required to perform or not.
  • JavaScript confirm dialogue box contains two buttons "Ok" and "Cancel".
  • If user clicks on OK button confirm dialogue box returns true. If user clicks on cancel button it returns false.
  • So based on the user entered option we can continue our program. So confirm dialogue box used to test an action is required or not from user.



  • Its not possible to change values of confirm dialogue box buttons from "Ok" and "Cancel"to "Yes" and "No".
  • We need to use custom popups or jquery popups to use "Yes" and "No".
  •   var res= confirm("Are you sure to continue?");

How to use Javascript  confirm dialogue box:

  1. function myFunction() {
  2.     var text;
  3.     var res= confirm("Are you sure to continue?");
  4.     if (res == true) {
  5.         text= "You clicked OK!";
  6.     } else {
  7.         text= "You clicked Cancel!";
  8.     }
  9.     document.getElementById("demo").innerHTML = txt
  10. }
  11. </script>

Javascript confirm delete onclick:

  • If we are deleting a record from database then we need to ask user  to confirm deletion if ye really want to delete record then user checks Ok otherwise cancel based on this we can proceed furthur.
  • To implement this functionality we need to call a JavaScript function onClick()  whenever user clicks on delete record button.

Program#1: JavaScript program to show confirm dialogue box on clicking delete student record.

  1. <!DOCTYPE html>
  2. <html>
  3. <body>
  4.  
  5. <p>Click the button to delete student record</p>
  6.  
  7. <button onclick="toConfirm()">Delete student record </button>
  8.  
  9. <p id="student"></p>
  10. <script>
  11. function toConfirm() {
  12.     var text;
  13.     var r = confirm("You clicked on a button to delete student recored. Clik ok ro proceed");
  14.     if (r == true) {
  15.        //code to delete student record.
  16.         text = "You clikced on ok. Student record deleted";
  17.     } else {
  18.         text = "You clicked on cancel. transaction cancelled.";
  19.     }
  20.     document.getElementById("student").innerHTML = text;
  21. }
  22. </script>
  23.  
  24. </body>
  25. </html>

javascript confirm delete yes no

  • If we click on Ok then it will delete student record. otherwise it wont.

javascript onclick confirm dialog

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,

How to take input from user in java using scanner

  • We are having special classes to take input from the user. One of the most commonly used class is java.util.Scanner.
  • We can read input from the console using scanner class.
  • Java.util.Scanner class provides lot of methods to take different typed of data from the user as input.
  • Scanner class is final class in java like String class. 
  • Scanner class implements Iterator and Closeable  interfaces.



Scanner class in Java

  1. public final class Scanner
  2. extends Object
  3. implements Iterator<String>, Closeable

  • In order to read or take input from user we need to create object of Scanner class by using its constructor which takes System.in as an argument.
  • By using methods of System class we can take different type of data like string , int and float etc.
  • scannerObject.nextInt() will accepts integer value as an input .
  • scannerObject.nextLong() will accepts long value as an input from user.
  • We also take different type of data by using  some delimiters 
  • Using useDelimiter() method we can give data by using delimiters.
  • Lets see what are the different methods in java.util.scanner class.

Java.util.Scanner class methods:

Scanner class in java user input.png


Scanner class in java programming:
  • Lets see some simple java programs to get input from user 
  • How to take integer input from user in java?
  • How to take input from user in java using scanner ?
  • How to take string input in java using scanner class?


Program #1: Write a java example program to read integer type of data as an input from the user from console using scanner class

  1. package com.scannerjava;

  2. import java.util.Scanner;

  3. public class TakeInputUsingScanner {

  4. /**
  5.    * @wesite:www.instanceofJava.com
  6.    * @category: Java program to take input from user using scanner
  7.    */
  8. public static void main(String[] args) {
  9.     Scanner sc= new Scanner(System.in);
  10.      System.out.println("Please enter any integer value as input");
  11.       int x=sc.nextInt();
  12.       System.out.println("Entered integer value is "+x);

  13. }
  14. }

 Output:

  1. Please enter any integer value as input
  2. 33
  3. Entered integer value is 33

Program #2: Write a java example program to read String type of data as an input from the user from console using scanner class


  1. package com.scannerjava;

  2. import java.util.Scanner;

  3. public class TakeInputUsingScanner {

  4. /**
  5.    * @wesite:www.instanceofJava.com
  6.    * @category: Java program to take input from user using scanner
  7.    */
  8. public static void main(String[] args) {
  9.     Scanner sc= new Scanner(System.in);
  10.      System.out.println("Please enter any Sting value as input");
  11.      String str=sc.next();
  12.       System.out.println("Entered String value is "+str);

  13. }
  14. }


 Output:

  1. Please enter any String value as input
  2. instanceofjava
  3. Entered String value is instanceofjava

Program #3: Write a java example program to read  data as an input from the user from console using scanner class with delimiters


  1. package com.scannerjava;

  2. import java.util.Scanner;

  3. public class TakeInputUsingScanner {

  4. /**
  5.    * @wesite:www.instanceofJava.com
  6.    * @category: Java program to take input from user using scanner
  7.    */
  8. public static void main(String[] args) {
  9.  
  10. String input = "top 10 java interview questions on scanner class";
  11.  Scanner sc = new Scanner(input).useDelimiter("\\s");  
  12.  
  13.      System.out.println(sc.next());  
  14.      System.out.println(sc.nextInt());  
  15.      System.out.println(sc.next());  
  16.      System.out.println(sc.next());  
  17.      System.out.println(sc.next());  
  18.      System.out.println(sc.next());  
  19.      System.out.println(sc.next());    
  20.       System.out.println(sc.next()); 
  21. }
  22. }


 Output:

  1. top
  2. 10
  3. java
  4. interview
  5. questions
  6. on
  7. scanner
  8. class

Program #4: Write a java example program to read  all type of data as an input from the user from console using scanner class

  1. package com.scannerjava;

  2. import java.util.Scanner;

  3. public class TakeInputUsingScanner {

  4. /**
  5.    * @wesite:www.instanceofJava.com
  6.    * @category: Java program to take input from user using scanner
  7.    */
  8. public static void main(String[] args) {
  9.  
  10. Scanner sc = new Scanner(System.in);
  11.  
  12.  System.out.println("Enter an integer value");
  13. System.out.println(sc.nextInt()); 
  14.  
  15. System.out.println("Enter a float value");
  16.  System.out.println(sc.nextFloat()); 
  17.  
  18.  System.out.println("Enter a Double value");
  19. System.out.println(sc.nextDouble()); 
  20.  
  21. System.out.println("Enter a Byte value");
  22. System.out.println(sc.nextByte()); 
  23.  
  24. System.out.println("Enter a Long value");
  25. System.out.println(sc.nextLong());
  26. }
  27. }


 Output:

  1. Enter an integer value
  2. 12
  3. 12
  4. Enter a float value
  5. 12.34
  6. 12.34
  7. Enter a Double value
  8. 12.3456789
  9. 12.3456789
  10. Enter a Byte value
  11. 2
  12. 2
  13. Enter a Long value
  14. 9876636363536
  15. 9876636363536

Program #5: Write a java example program how to read input from console in java eclipse  all type of data as an input from the user from console using scanner class.

java util scanner

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

How to create csv file in java using filewriter

  • We can create CSV file and fill some data in to it using java program.
  • We can create CSV file and write data int to CSV file using java.io.FileWriter class.
  • Creating object of java.io.FileWriter class by giving output filename.
  • After creating object of java.io.FileWriter append data by calling append("data") method of FileWriter class object.
  • Use append('\n'); for enter data in new row.
  • Lets see a java example program on how to create csv file and write data in to it using FileWriter Class.



Program #1: Java program to create CSV file using FileWriter class

  1. package com.java.createcsvfile;

  2. import java.io.FileWriter;
  3. import java.io.IOException;

  4. public class CreateCsvFile {

  5. private static void generateCsvFile(String fileName) {

  6.       FileWriter writer = null;

  7.  try {

  8.      writer = new FileWriter(fileName);
  9.      writer.append("Name");
  10.      writer.append(',');
  11.      writer.append("Number");
  12.      writer.append('\n');

  13.      writer.append("interview questions");
  14.      writer.append(',');
  15.      writer.append("001");
  16.      writer.append('\n');

  17.   writer.append("interview programs");
  18.   writer.append(',');
  19.   writer.append("002");
  20.   writer.append('\n');

  21.   System.out.println("CSV file is created...");

  22.   } catch (IOException e) {
  23.   e.printStackTrace();
  24.   } finally {
  25.         try {
  26.    writer.flush();
  27.    writer.close();
  28.         } catch (IOException e) {
  29.    e.printStackTrace();
  30. }
  31. }
  32. }

  33. public static void main(String[] args) {

  34. String location = "E:\\newCsvFile.csv";
  35. generateCsvFile(location);

  36. }

  37. }

 Output:


create csv file in java
Select Menu