Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * To change this license header, choose License Headers in Project Properties.
- * To change this template file, choose Tools | Templates
- * and open the template in the editor.
- */
- package insertionsort;
- import java.util.Scanner;
- /**
- *
- * @author manth
- */
- public class InsertionSort {
- /**
- * @param args the command line arguments
- */
- static int n;
- static double input[];
- static String ALGO="InsertionSort";
- public static void main(String[] args) {
- //input();
- randinput();
- System.out.println(" INPUT IS ");
- display(input);
- input=insertionsort(input);
- System.out.println("OUTPUT OF SORTED NUMBERS IS ");
- System.out.println("Numbers are sorted by "+ ALGO);
- display(input);
- }
- public static double[] insertionsort(double input[])
- {
- long startTime = System.currentTimeMillis();
- int count=0;
- for(int i=1;i<input.length;i++)
- {
- for(int j=i;j>0;j--)
- {
- if(input[j]<input[j-1])
- {
- double temp=input[j];
- input[j]=input[j-1];
- input[j-1]=temp;
- count++;
- }
- else
- break;
- }
- }
- System.out.println(count +" passes");
- long endTime=System.currentTimeMillis();
- System.out.println("\n\n time elapsed in sorting is "+ (endTime-startTime)+" Milliseconds \n\n");
- return input;
- }
- public static void display(double [] input)
- {
- for(int i=0;i<input.length;i++)
- {
- System.out.println(input[i]+" ");
- }
- }
- public static void randinput()
- {
- Scanner sc=new Scanner(System.in);
- System.out.println(" BUBBLE SORT \n ENTER TOTAL NUMBERS TO SORT");
- try{
- n=Integer.parseInt(sc.nextLine());
- }catch(Exception e)
- {
- System.out.println(" Please Enter a valid integer "+e);
- }
- input=new double[n];
- for(int i=0;i<n;i++)
- {
- input[i]=Math.random()*1000;
- }
- }
- public static void input()
- {
- Scanner sc=new Scanner(System.in);
- System.out.println(" \n ENTER TOTAL NUMBERS TO SORT");
- try{
- n=Integer.parseInt(sc.nextLine());
- }catch(Exception e)
- {
- System.out.println(" Please Enter a valid integer "+e);
- }
- input=new double[n];
- for(int i=0;i<n;i++)
- {
- input[i]=sc.nextInt();
- }
- System.out.println(" INPUT RECORDED ");
- System.out.println(" Numbers are getting sorted by algorithm: "+ ALGO);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment