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

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

How to find uppercase letters in a string in java

  • How can we count upper case letter in String  java ?
  • How to find uppercase letters in String  java?
  • How to find capital letters in string in java?
  • How u discover the capital letter given sentence?
  • Yes We can find uppercase or capital letters in a String using isUpperCase() method of Character class in java
  • In order to find number of uppercase letters in a string of all capital letters in a string we need to iterate all characters of a string in a loop and check individual characters are uppercase letters or not using Character class provided isUpperCase() method.
  • To find the uppercase letters in a string in Java, you can use the isUpperCase() method of the Character class.




Program #1: Java example program to find all capital letters / Uppercase letters in a String


  1. package findUppercaseletters.String;
  2. public class FinfUppercaseLetters {
  3.  
  4.     /**
  5.      * @website: www.instanceofjava.com
  6.      */
  7.  
  8.  public static void main(String[] args) {
  9.         
  10.         
  11.   String str= "How to Print Uppercase Letters in Java";
  12.  
  13.     for (int i = 0; i < str.length(); i++) {
  14.     
  15.             if(Character.isUpperCase(str.charAt(i))){    
  16.             System.out.println(str.charAt(i));
  17.             }
  18.             
  19.  }
  20.  
  21. }
  22.  
  23. }

 Output:


  1. H
  2. P
  3. U
  4. L
  5. J
  • Above code will print all the uppercase letters in the string.
  • Alternatively, you can also use the toUpperCase() method of the Character class to convert all the characters in the string to uppercase and then use the equals() method to compare them to the original character.
Program #2: Java example program to count number of upperCase letters in a String


how to find uppercase letters in a string in java

Select Menu