Skip to content

Commit c5a8531

Browse files
committed
refactor: refactor insertion sort
1 parent 43c2555 commit c5a8531

File tree

2 files changed

+15
-29
lines changed

2 files changed

+15
-29
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,15 @@
11
package com.example.algorithm.sort;
22

33
public class InsertionSort {
4-
public static int[] insertionSort(int[] array) {
5-
for (var i = 1; i < array.length; i++) {
6-
var key = array[i];
7-
var j = i - 1;
8-
while ((j > -1) && (array[j] > key)) {
4+
public static <T extends Comparable<T>> void insertionSort(T[] array) {
5+
for (int i = 1; i < array.length; i++) {
6+
T key = array[i];
7+
int j = i - 1;
8+
while ((j > -1) && (array[j].compareTo(key) > 0)) {
99
array[j + 1] = array[j];
1010
j--;
1111
}
1212
array[j + 1] = key;
1313
}
14-
return array;
15-
}
16-
17-
public static Double[] insertionSort(Double[] array) {
18-
for (var i = 1; i < array.length; i++) {
19-
var key = array[i];
20-
var j = i - 1;
21-
while ((j > -1) && (array[j] > key)) {
22-
array[j + 1] = array[j];
23-
j--;
24-
}
25-
array[j + 1] = key;
26-
}
27-
return array;
2814
}
2915
}
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,27 @@
11
package com.example.algorithm.sort;
22

33
import org.junit.jupiter.api.AfterEach;
4-
import org.junit.jupiter.api.BeforeEach;
54
import org.junit.jupiter.api.Test;
65

76
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
87

98
class InsertionSortTest {
10-
int[] array;
11-
12-
@BeforeEach
13-
void setUp() {
14-
array = new int[]{64, 32, 16, 8, 4};
15-
}
16-
179
@AfterEach
1810
void tearDown() {
1911
System.gc();
2012
}
2113

2214
@Test
2315
void testInsertionSort() {
24-
var result = InsertionSort.insertionSort(array);
25-
assertArrayEquals(new int[]{4, 8, 16, 32, 64}, result);
16+
var array = new Integer[]{64, 32, 16, 8, 4};
17+
InsertionSort.insertionSort(array);
18+
assertArrayEquals(new Integer[]{4, 8, 16, 32, 64}, array);
19+
}
20+
21+
@Test
22+
void testInsertionSort2() {
23+
var array = new Double[]{64.5, 32.5, 16.5, 8.5, 4.5};
24+
InsertionSort.insertionSort(array);
25+
assertArrayEquals(new Double[]{4.5, 8.5, 16.5, 32.5, 64.5}, array);
2626
}
2727
}

0 commit comments

Comments
 (0)