Skip to content

Commit 361aa27

Browse files
authored
Create java.md
1 parent 6e78cf2 commit 361aa27

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

java.md

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

0 commit comments

Comments
 (0)