-
Notifications
You must be signed in to change notification settings - Fork 215
/
Copy pathinsertion_sort.java
58 lines (46 loc) · 1.55 KB
/
insertion_sort.java
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
46
47
48
49
50
51
52
53
54
55
56
57
58
/*
Implementation of insertion sort in Java.
Insertion sort is a simple sorting algorith that iterates through
the list starting at the second element. We compare each element
to the preceding elements, slide over the preceding larger (or smaller)
elements, and insert the original element into the empty position.
Time Complexity worst-case and average complexity O(n^{2})
Insertion sort is inefficient for large arrays. However it is fast for
small arrays and typically more efficient than bubble sort and selection
sort due to not making as many comparisons on average.
Source: https://en.wikipedia.org/wiki/Insertion_sort
Sample input: [0, 2, 1,-1, 10, 3, 4]
Output: [-1 0 1 2 3 4 10]
*/
import java.util.Arrays;
class InsertionSort
{
void insertionSort(int array[])
{
int size = array.length;
for (int step = 1; step < size; step++)
{
int key = array[step];
int j = step - 1;
// Compare key with each element on the left of it until an element smaller than
// it is found.
// For descending order, change key<array[j] to key>array[j].
while (j >= 0 && key < array[j])
{
array[j + 1] = array[j];
--j;
}
// Place key at after the element just smaller than it.
array[j + 1] = key;
}
}
// Driver code
public static void main(String args[])
{
int[] data = { 9, 5, 1, 4, 3 };
InsertionSort is = new InsertionSort();
is.insertionSort(data);
System.out.println("Sorted Array in Ascending Order: ");
System.out.println(Arrays.toString(data));
}
}