Advertisement
rahman_shuvo_10

Insertion Sorting

Nov 20th, 2017
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.29 KB | None | 0 0
  1. import java.security.SecureRandom;
  2. import java.util.Scanner;
  3.  
  4. public class InsertionSortingShuvo {
  5. public static void InsertionSort(int[] list)
  6.     {
  7.         int index,previous_index,key,temp ;
  8.         int low = 0 ;
  9.         int high = list.length ;
  10.        
  11.         for(index = low ; index < high ; index++)
  12.         {
  13.             previous_index = index - 1 ;
  14.             key = list[index] ;
  15.            
  16.             while(previous_index >= 0 && key < list[previous_index])
  17.             {
  18.                 temp = list[previous_index] ;
  19.                 list[previous_index] = list[previous_index+1] ;
  20.                 list[previous_index+1] = temp ;
  21.                
  22.                 previous_index-- ;
  23.             }
  24.         }
  25.     }
  26.    
  27.     public static void printlist(int[] list)
  28.     {
  29.         for(int i = 0 ; i < list.length ; i++)
  30.             System.out.print(list[i]+" ");
  31.         System.out.println();
  32.     }
  33.  
  34.     public static void main(String[] args) {
  35.        
  36.         SecureRandom secureRandom = new SecureRandom() ;
  37.         Scanner input = new Scanner(System.in) ;
  38.         System.out.print("Enter list size : ");
  39.         int size = input.nextInt() ;
  40.        
  41.         int[] list = new int[size] ;
  42.        
  43.         //populating list with random numbers
  44.         for(int i = 0 ; i < list.length ; i++)
  45.             list[i] = secureRandom.nextInt(90) ;
  46.        
  47.         printlist(list);
  48.        
  49.         System.out.println("after sorting : ");
  50.        
  51.         //BubbleSort(list) ;
  52.         InsertionSort(list);
  53.        
  54.         printlist(list);
  55.        
  56.         input.close();
  57.  
  58.     }
  59.  
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement