-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathInsertion_Sort.java
58 lines (48 loc) · 1.24 KB
/
Insertion_Sort.java
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import java.util.*;
public class Insertion_Sort {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while(t-- > 0){
int n = sc.nextInt();
int[] arr = new int[n];
for(int i = 0; i<n; i++){
arr[i] = sc.nextInt();
}
RInsertionSort(arr, n);
print(arr);
}
}
// Interative
public static void insertionSort(int[] arr, int n){
for(int i = 1; i<n; i++){
int key = arr[i];
int j = i - 1;
while( j >= 0 && arr[j] > key ){
arr[j+1] = arr[j];
j = j-1;
}
arr[j+1] = key;
}
}
// Recurssive
public static void RInsertionSort(int[] arr, int n){
if( n <= 1 ){
return;
}
RInsertionSort(arr, n-1);
int key = arr[n-1];
int j = n - 2;
while( j >= 0 && arr[j] > key ){
arr[j+1] = arr[j];
j = j-1;
}
arr[j+1] = key;
}
public static void print(int[] arr){
for(int i : arr){
System.out.print(i + " ");
}
System.out.println();
}
}