forked from examplehub/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInsertionSort.java
More file actions
41 lines (38 loc) · 944 Bytes
/
InsertionSort.java
File metadata and controls
41 lines (38 loc) · 944 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
38
39
40
41
package com.examplehub.sorts;
public class InsertionSort implements Sort {
/**
* InsertionSort algorithm implements.
*
* @param numbers the numbers to be sorted.
*/
public void sort(int[] numbers) {
for (int i = 1; i < numbers.length; ++i) {
int j = i - 1;
int key = numbers[i];
while (j >= 0 && key < numbers[j]) {
numbers[j + 1] = numbers[j];
--j;
}
if (j != i - 1) {
numbers[j + 1] = key;
}
}
}
/**
* Generic InsertionSort algorithm implements.
*
* @param array the array to be sorted.
* @param <T> the class of the objects in the array.
*/
public <T extends Comparable<T>> void sort(T[] array) {
for (int i = 1; i < array.length; ++i) {
int j = i - 1;
T key = array[i];
while (j >= 0 && key.compareTo(array[j]) < 0) {
array[j + 1] = array[j];
--j;
}
array[j + 1] = key;
}
}
}