-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathProblem$08.java
66 lines (57 loc) · 1.92 KB
/
Problem$08.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
59
60
61
62
63
64
65
66
package chapter_twenty_three;
import java.util.Arrays;
import java.util.Comparator;
/**
* 23.8 (Generic insertion sort) Write the following two generic methods using insertion
* sort. The first method sorts the elements using the Comparable interface, and
* the second uses the Comparator interface.
* public static <E extends Comparable<E>>
* void insertionSort(E[] list)
* public static <E> void insertionSort(E[] list,
* Comparator<? super E> comparator)
*
*
* @author Sharaf Qeshta
* */
public class Problem$08
{
public static void main(String[] args)
{
// test insertionSort(E[] list)
Integer[] list = {-44, -5, -3, 3, 3, 1, -4, 0, 1, 2, 4, 5, 53};
insertionSort(list);
/*
* [-44, -5, -4, -3, 0, 1, 1, 2, 3, 3, 4, 5, 53]
* */
System.out.println(Arrays.toString(list));
// test insertionSort(E[] list, Comparator<?super E> comparator)
Integer[] list2 = {-44, -5, -3, 3, 3, 1, -4, 0, 1, 2, 4, 5, 53};
insertionSort(list2, (o1, o2) -> o1 - o2);
/*
* [-44, -5, -4, -3, 0, 1, 1, 2, 3, 3, 4, 5, 53]
* */
System.out.println(Arrays.toString(list2));
}
public static <E extends Comparable<E>> void insertionSort(E[] list)
{
for (int i = 1; i < list.length; i++)
{
E currentElement = list[i];
int k;
for (k = i - 1; k >= 0 && list[k].compareTo(currentElement) > 0; k--)
list[k + 1] = list[k];
list[k + 1] = currentElement;
}
}
public static <E> void insertionSort(E[] list, Comparator<?super E> comparator)
{
for (int i = 1; i < list.length; i++)
{
E currentElement = list[i];
int k;
for (k = i - 1; k >= 0 && comparator.compare(list[k], currentElement) > 0; k--)
list[k + 1] = list[k];
list[k + 1] = currentElement;
}
}
}