0% found this document useful (0 votes)
79 views

Import Public Class Int Static New Public Static Void Int Int Int Int For

This Java code implements insertion sort. It takes in an array as a parameter, loops through the array, and for each element compares it to the elements before it, swapping elements into sorted order. It prompts the user to enter the size of and values for an integer array, sorts the array using the insertion sort method, and prints the array before and after sorting.

Uploaded by

sara amer
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
79 views

Import Public Class Int Static New Public Static Void Int Int Int Int For

This Java code implements insertion sort. It takes in an array as a parameter, loops through the array, and for each element compares it to the elements before it, swapping elements into sorted order. It prompts the user to enter the size of and values for an integer array, sorts the array using the insertion sort method, and prints the array before and after sorting.

Uploaded by

sara amer
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

insertion_sort.

java

1 import java .util.Scanner;


2
3 public class insertion_sort {
4 int a [];
5 static Scanner scan = new Scanner (System.in) ;
6 public static void Insertion (int[] aa) {
7 int n = aa.length;
8 int j, i;
9 int m =0;
10 for(i = 1 ; i<=n-1 ; i++){
11 m=aa[i];
12 j=i-1;
13 while (j>=0 && aa[j]>m){
14 aa[j+1] =aa[j];
15 j--;
16 }
17 aa[j+1]=m;
18 }//end for
19
20 System.out.println( "after sorting" );
21 System.out.println("");
22
23 for(int k = 0 ; k<=n-1 ; k++)
24
25 System.out.print( "a["+(k)+"]"+ "=" + aa[k] +" " );
26
27 }//end method
28
29
30
31
32
33 public static void main (String args[]){
34 System.out.println("Hello I'm insertion sort my operation basic is sorted array ");
35 System.out.println("");
36 System.out.println("Time efficiency : O(n^2) & space efficiency : O(1)");
37 System.out.println("");
38 System.out.println( "Pleas enter size array " );
39 System.out.println("");
40
41 int n=scan.nextInt(); // length array
42
43 int a []=new int [n]; //array
44
45 // add values to array
46
47 for(int i = 0 ; i<=n-1 ; i++){
48 System.out.println( "Pleas enter value "+ (i+1) + " into array" );
49 System.out.println("");
50
51 int s= scan .nextInt();
52 a[i]=s;
53 }
54 System.out.println( "befor sorting : " );
55 System.out.println("");
56
57 for(int k = 0 ; k<=n-1 ; k++)
58
59 System.out.print( "a["+k+"]"+ "=" + a[k] +" " );
60 System.out.println("");
61 System.out.println("");
62 Insertion(a);}}

Page 1

You might also like