Skip to content

Commit a11f5c3

Browse files
authored
Create InsertionSort.java
1 parent 3a25938 commit a11f5c3

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

sorting/InsertionSort.java

+52
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
/**
2+
* Java implementation of insertion sort
3+
*
4+
* @author Andres Langberg
5+
*/
6+
7+
8+
// Java program for implementation of Insertion Sort
9+
public class InsertionSort
10+
{
11+
/*Function to sort array using insertion sort*/
12+
void sort(int arr[])
13+
{
14+
int n = arr.length;
15+
for (int i=1; i<n; ++i)
16+
{
17+
int key = arr[i];
18+
int j = i-1;
19+
20+
/* Move elements of arr[0..i-1], that are
21+
greater than key, to one position ahead
22+
of their current position */
23+
while (j>=0 && arr[j] > key)
24+
{
25+
arr[j+1] = arr[j];
26+
j = j-1;
27+
}
28+
arr[j+1] = key;
29+
}
30+
}
31+
32+
/* A utility function to print array of size n*/
33+
static void printArray(int arr[])
34+
{
35+
int n = arr.length;
36+
for (int i=0; i<n; ++i)
37+
System.out.print(arr[i] + " ");
38+
39+
System.out.println();
40+
}
41+
42+
// Driver method
43+
public static void main(String args[])
44+
{
45+
int arr[] = {12, 11, 13, 5, 6};
46+
47+
InsertionSort ob = new InsertionSort();
48+
ob.sort(arr);
49+
50+
printArray(arr);
51+
}
52+
}

0 commit comments

Comments
 (0)