-
Notifications
You must be signed in to change notification settings - Fork 0
/
Insertion sort
45 lines (36 loc) · 866 Bytes
/
Insertion sort
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
//Insertion sort
import java.util.*;
import java.lang.Math;
class Sorting {
static void printArray(int arr[], int size) {
for(int i = 0; i < size; i++)
System.out.print(arr[i] + " ");
System.out.println();
}
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while(t > 0) {
int n = sc.nextInt();
int a[] = new int[n];
for(int i = 0; i < n; i++)
a[i]n= sc.nextInt();
new Solution().insertionSort(a,nn);
printArray(a,nn);
t--;
}
}
}
class Solution {
public 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--;
}
arr[j + 1] = key;
}
}
}