-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInsertionSort.java
More file actions
44 lines (42 loc) · 1.17 KB
/
Copy pathInsertionSort.java
File metadata and controls
44 lines (42 loc) · 1.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import java.util.Scanner;
/*
* ---------------
* Time Complexity
* Best case = O(n)
* Worst, Average case = O(n^2)
* ---------------
*/
public class InsertionSort {
public static void main(String []args){
try (Scanner scan = new Scanner(System.in)) {
System.out.println("Enter the size:");
int size = scan.nextInt();
int arr[] = new int[size];
System.out.println("Enter the elements:");
for(int i=0;i<size;i++){
arr[i] = scan.nextInt();
}
sort(arr,size);
/*for(int i=0;i<size;i++){
System.out.print(arr[i]+" ");
}*/
}
}
static void sort(int arr[], int n){
int j, temp;
for(int i=1;i<n;i++){
temp = arr[i];
j = i-1;
while(j>=0 && arr[j]>temp){
arr[j+1] = arr[j];
j--;
}
System.out.println(j);
arr[j+1] = temp;
for(j=0;j<n;j++){
System.out.print(arr[j]+" ");
}
System.out.println();
}
}
}