Skip to content

Commit 5e7b34c

Browse files
Merge pull request #190 from tandrimasingha/master
Create insertion_sort.java
2 parents fe4194a + a6eb2b6 commit 5e7b34c

1 file changed

Lines changed: 38 additions & 0 deletions

File tree

Sorting/insertion_sort.java

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
// Java program for implementation of Insertion Sort
2+
class InsertionSort {
3+
//Function to sort array using insertion sort
4+
void sort(int arr[])
5+
{
6+
int n = arr.length;//checking the length of array
7+
for (int i = 1; i < n; ++i) {
8+
int m = arr[i];
9+
int j = i - 1;
10+
// Move elements of arr[0..i-1], that are greater than key, to one position ahead of their current position
11+
while (j >= 0 && arr[j] > m) {
12+
arr[j + 1] = arr[j];
13+
j = j - 1;
14+
}
15+
arr[j + 1] = m;
16+
}
17+
}
18+
// function to print the array
19+
static void printArray(int arr[])
20+
{
21+
int n = arr.length;
22+
for (int i = 0; i < n; ++i)
23+
System.out.print(arr[i] + " ");
24+
25+
System.out.println();
26+
}
27+
28+
// main method where we take input and call the function from above
29+
public static void main(String args[])
30+
{
31+
int arr[] = { 34, 1, 130, 15, 6 };
32+
33+
InsertionSort ob = new InsertionSort();
34+
ob.sort(arr);
35+
36+
printArray(arr);
37+
}
38+
}

0 commit comments

Comments
 (0)