-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathInsertionSort.java
More file actions
37 lines (31 loc) · 771 Bytes
/
InsertionSort.java
File metadata and controls
37 lines (31 loc) · 771 Bytes
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
package Sorting;
public class InsertionSort {
public static void main(String[] args) {
int arr[] = { -2, 3, 4, -1, 5, -12, 6, 1, 3 };
insertion_sort(arr);
print(arr);
}
static void insertion_sort(int arr[])
{
int n = arr.length;
for(int i=1;i<n;i++)
{
int current = arr[i];
int prev = i - 1;
while(prev >= 0 && arr[prev] > current)
{
arr[prev + 1] = arr[prev];
prev = prev - 1;
}
arr[prev + 1] = current;
}
}
static void print(int arr[])
{
int n = arr.length;
for(int i=0;i<n;i++)
{
System.out.print(arr[i] + " ");
}
}
}