import java.util.*; public class Insertion { static void quicksort(int a[],int left,int right) { int x,j; for(int i=1;i<=a.length-1;i++) { x=a[i];j=i; while(j>0&&a[j-1]>x) { a[j]=a[j-1]; j=j-1; } a[j]=x; } } public static void main(String args[]) { System.out.println("Enter number of elements"); Scanner s=new Scanner(System.in); int n=s.nextInt(); int a[]=new int[n]; for(int i=0;i<n;i++) { System.out.println("Enter element"+(i+1)); a[i]=s.nextInt(); } quicksort(a, 0, n-1); for(int i=0;i<=n-1;i++) System.out.println(a[i]); }//end of main }//end of Insertion OUTPUT =================================================== C:\Program Files\Java\jdk1.7.0_02\bin>javac Insertion.java C:\Program Files\Java\jdk1.7.0_02\bin>java Insertion Enter number of elements 5 Enter element1 9878 Enter element2 4545 Enter element3 45487 Enter element4 545 Enter element5 665 545 665 4545 9878 45487
Tuesday, 21 August 2012
To implement insertion sort.
import java.util.*; public class Insertion { static void quicksort(int a[],int left,int right) { int x,j; for(int i=1;i<=a.length-1;i++) { x=a[i];j=i; while(j>0&&a[j-1]>x) { a[j]=a[j-1]; j=j-1; } a[j]=x; } } public static void main(String args[]) { System.out.println("Enter number of elements"); Scanner s=new Scanner(System.in); int n=s.nextInt(); int a[]=new int[n]; for(int i=0;i<n;i++) { System.out.println("Enter element"+(i+1)); a[i]=s.nextInt(); } quicksort(a, 0, n-1); for(int i=0;i<=n-1;i++) System.out.println(a[i]); }//end of main }//end of Insertion OUTPUT =================================================== C:\Program Files\Java\jdk1.7.0_02\bin>javac Insertion.java C:\Program Files\Java\jdk1.7.0_02\bin>java Insertion Enter number of elements 5 Enter element1 9878 Enter element2 4545 Enter element3 45487 Enter element4 545 Enter element5 665 545 665 4545 9878 45487
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment