所以我try 使用整型、双精度和字符值来练习实现插入排序算法,我能够对我的列表进行排序,但是我的原始列表显示了错误的结果.应该在我的代码中显示来自Test1、Test2、Test3的数据值.谁能告诉我,因为我已经被困了很长一段时间,我错过了什么?
import java.util.ArrayList;
public class InsertionSort<E extends Comparable<E>> {
public void insertionSort(ArrayList<E> list) {
int n = list.size();
for (int i = 1; i < n; i++) {
E key = list.get(i);
int j = i - 1;
while (j >= 0 && list.get(j).compareTo(key) > 0) {
list.set(j + 1, list.get(j));
j--;
}
list.set(j + 1, key);
}
}
public static void main(String[] args) {
int[] test1 = {3, 5, 2, 4, 1, 8, 7, 6, 9};
double[] test2 = {1.99, 2.05, 9.01, 6.49, 3.14, 5.55};
char[] test3 = "algorithm".toCharArray();
ArrayList<Integer> list1 = new ArrayList<>();
for (int num : test1) {
list1.add(num);
}
InsertionSort<Integer> integerSorter = new InsertionSort<>();
integerSorter.insertionSort(list1);
System.out.println("Test Example 1");
System.out.println("Original List: " + list1);
System.out.println("Sorted List: " + list1);
ArrayList<Double> list2 = new ArrayList<>();
for (double num : test2) {
list2.add(num);
}
InsertionSort<Double> doubleSorter = new InsertionSort<>();
doubleSorter.insertionSort(list2);
System.out.println("\nTest Example 2");
System.out.println("Original List: " + list2);
System.out.println("Sorted List: " + list2);
ArrayList<Character> list3 = new ArrayList<>();
for (char ch : test3) {
list3.add(ch);
}
InsertionSort<Character> charSorter = new InsertionSort<>();
charSorter.insertionSort(list3);
System.out.println("\nTest Example 3");
System.out.println("Original List: " + list3);
System.out.println("Sorted List: " + list3);
}
}