forked from examplehub/Java
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathInsertionSort.java
More file actions
41 lines (38 loc) · 1012 Bytes
/
InsertionSort.java
File metadata and controls
41 lines (38 loc) · 1012 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 insertValue = numbers[i];
int j;
for (j = i - 1; j >= 0 && insertValue < numbers[j]; --j) {
numbers[j + 1] = numbers[j];
}
if (j != i - 1) {
numbers[j + 1] = insertValue;
}
}
}
/**
* 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) {
T insertValue = array[i];
int j;
for (j = i - 1; j >= 0 && insertValue.compareTo(array[j]) < 0; --j) {
array[j + 1] = array[j];
}
if (j != i - 1) {
array[j + 1] = insertValue;
}
}
}
}