归并排序:
之前使用LinkedList作为承载,现在使用Object[]来作为承载。
package com.xiva.demo.sort;
import java.util.Arrays;
public class SortPractice<E extends Comparable<E>> {
@SuppressWarnings("unchecked")
public void merge(E[] array, int low, int high) {
int mid = (high + low) / 2;
int s1 = low;
int s2 = mid + 1;
System.out.println("len:" + (high - low));
Object[] tempArr = new Object[high - low + 1];
int tempIdx = 0;
while (s1 <= mid && s2 <= high) {
if (array[s1].compareTo(array[s2]) <= 0) {
tempArr[tempIdx] = array[s1++];
tempIdx++;
} else {
tempArr[tempIdx] = array[s2++];
tempIdx++;
}
}
if (s1 <= mid) {
for (int i = s1; i <= mid; i++) {
tempArr[tempIdx] = array[i];
tempIdx++;
}
}
if (s2 <= high) {
for (int i = s2; i <= high; i++) {
tempArr[tempIdx] = array[i];
tempIdx++;
}
}
System.out.println(Arrays.toString(tempArr) + low + ":" + high);
for (int i = 0; i < tempArr.length; i++) {
array[low + i] = (E) tempArr[i];
}
}
public void mergeSort(E[] array, int low, int high) {
if (low < high) {
mergeSort(array, low, (high + low) / 2);
mergeSort(array, (high + low) / 2 + 1, high);
merge(array, low, high);
}
}
public static void main(String[] args) {
SortPractice<Integer> sort = new SortPractice<Integer>();
Integer num01 = new Integer(12);
Integer num02 = new Integer(13);
Integer num03 = new Integer(44);
Integer num04 = new Integer(3);
Integer num05 = new Integer(13);
Integer num06 = new Integer(5);
Integer num07 = new Integer(7);
Integer[] array = { num01, num02, num03, num04, num05, num06, num07,
num04 };
sort.mergeSort(array, 0, array.length - 1);
System.out.println(Arrays.toString(array));
}
}