插入排序算法的JAVA实现

1,对元素进行排列时,元素之间需要进行比较,因此需要实现Comparable<T>接口。即,<T extends Comparable<T>>. 更进一步,如果允许待比较的类型可以和它的父类型进行比较,则需要写成:<T extends Comparable<? super T>, 其中<? super T> 表示 T 的任意超类。

2,InsertionSortArray.java 类实现了从小到大顺序以插入排序的方式对数据进行排序。

3,insertionSort方法负责对每一个元素进行排序,insertInOrder方法将待排序的元素插入到合适的位置,相当于执行具体的操作。

具体代码如下:

public class InsertionSortArray {
public static <T extends Comparable<? super T>> void insertSort(T[] a, int n){
insertionSort(a, 0, n - 1);//对序列a进行排序,其起始索引为0,最后元素的索引为n-1
} //从索引first到last执行插入排序
private static <T extends Comparable<? super T>> void insertionSort(T[] a, int first, int last){
for(int unsorted = first + 1; unsorted <= last; unsorted++){//插入排序中第一个元素视为有序,故从第二个元素开始
T firstUnsorted = a[unsorted];//获得待排序的元素
insertInOrder(firstUnsorted, a, first, unsorted - 1);//将之插入到合适的位置
}
} //将element插入到已经排好序的,起始位置为begin,终止位置为end的 序列中
private static <T extends Comparable<? super T>> void insertInOrder(T element, T[] a, int begin, int end){
int index = end;
//待插入的元素依次从后往前与已排序好的元素进行比较,直至找到比它小的元素为止
while((index >= begin) && (element.compareTo(a[index]) < 0)){
a[index + 1] = a[index];//将元素后移一位,a[index+1]其实就是element
index--;
}
a[index + 1] = element;//将element插入到合适的位置
}
}

4,在实现排序时,我们使用了泛型。使用泛型的好处是:对于任何类型的对象,只要它实现了Comparable接口,就可以通过调用compareTo方法对之进行比较。

因此,它还可以对自定义类型的对象进行排序,只要你定义的类实现Comparable接口就可以了。

以下测试类中定义了String类型数组和Integer类型的数组,并都可以调用插入排序的方法进行排序,代码如下:

public class TestSort {
public static void main(String[] args) {
String[] arr = {"hello","world","hadoop","hbase","hive"};
InsertionSortArray.insertSort(arr, arr.length);
System.out.println("字符串排序结果");
for(String str : arr)
System.out.println(str);
Integer[] integer = {1,5,3,8,10,4};
InsertionSortArray.insertSort(integer, integer.length);
System.out.println("整数排序结果");
for(int i : integer)
System.out.println(i);
}
}
上一篇:「Django」rest_framework学习系列-API访问跨域问题


下一篇:TeamViewer一直显示“未就绪,请检查您的连接”什么原因?