Skip to content

Commit 09f9f80

Browse files
Merge pull request #625 from Joseph-Acevedo/java_insertionsort
Added insertion sort in java using generics
2 parents 1c1a845 + eacff62 commit 09f9f80

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/**
2+
*
3+
* Sorts a list of generic Comparables using Insertion Sort
4+
*
5+
*/
6+
public class InsertionSort {
7+
8+
/**
9+
* Sorts a list of elements that extend comparable using insertion sort
10+
* algorithm
11+
* @param list A list of Comparables to be sorted
12+
*/
13+
public static <T extends Comparable<T>> void insertionSort (T[] list)
14+
{
15+
int size = list.length;
16+
int outCounter, inCounter;
17+
T temp;
18+
// Sort list[] into increasing order.
19+
for (outCounter = 1; outCounter < size; outCounter++)
20+
{
21+
temp = list[outCounter];
22+
for (inCounter = outCounter; inCounter > 0 && list[inCounter - 1].compareTo(temp) > 0; inCounter--)
23+
{
24+
list[inCounter] = list[inCounter - 1];
25+
}
26+
list[inCounter] = temp;
27+
}
28+
}
29+
}

0 commit comments

Comments
 (0)