1.概念:
归并(Merge)排序法是将两个(或两个以上)有序表合并成一个新的有序表,即把待排序序列分为若干个有序的子序列,再把有序的子序列合并为整体有序序列。
2.归并操作:
3.示例代码:
//排序器
/**
* 排序器接口(策略模式: 将算法封装到具有共同接口的独立的类中使得它们可以相互替换)
*
*
*/
public interface Sorter {
/**
* 排序
* @param list 待排序的数组
*/
public <T extends Comparable<T>> void sort(T[] list);
/**
* 排序
* @param list 待排序的数组
* @param comp 比较两个对象的比较器
*/
public <T> void sort(T[] list, Comparator<T> comp);
}
public class MergeSorter implements Sorter {
@Override
public <T extends Comparable<T>> void sort(T[] list) {
T[] temp = (T[]) new Comparable[list.length];
mSort(list, temp, 0, list.length - 1);
}
private <T extends Comparable<T>> void mSort(T[] list, T[] temp, int low, int high) {
if(low == high) {
return ;
}
else {
int mid = low + ((high - low) >> 1);
mSort(list, temp, low, mid);
mSort(list, temp, mid + 1, high);
merge(list, temp, low, mid + 1, high);
}
}
private <T extends Comparable<T>> void merge(T[] list, T[] temp, int left, int right, int last) {
int j = 0;
int lowIndex = left;
int mid = right - 1;
int n = last - lowIndex + 1;
while (left <= mid && right <= last) {
if (list[left].compareTo(list[right]) < 0) {
temp[j++] = list[left++];
} else {
temp[j++] = list[right++];
}
}
while (left <= mid) {
temp[j++] = list[left++];
}
while (right <= last) {
temp[j++] = list[right++];
}
for (j = 0; j < n; j++) {
list[lowIndex + j] = temp[j];
}
}
@Override
public <T> void sort(T[] list, Comparator<T> comp) {
T[] temp = (T[]) new Comparable[list.length];
mSort(list, temp, 0, list.length - 1, comp);
}
private <T> void mSort(T[] list, T[] temp, int low, int high, Comparator<T> comp) {
if(low == high) {
return ;
}
else {
int mid = low + ((high - low) >> 1);
mSort(list, temp, low, mid, comp);
mSort(list, temp, mid + 1, high, comp);
merge(list, temp, low, mid + 1, high, comp);
}
}
private <T> void merge(T[] list, T[] temp, int left, int right, int last, Comparator<T> comp) {
int j = 0;
int lowIndex = left;
int mid = right - 1;
int n = last - lowIndex + 1;
while (left <= mid && right <= last) {
if (comp.compare(list[left], list[right]) < 0) {
temp[j++] = list[left++];
} else {
temp[j++] = list[right++];
}
}
while (left <= mid) {
temp[j++] = list[left++];
}
while (right <= last) {
temp[j++] = list[right++];
}
for (j = 0; j < n; j++) {
list[lowIndex + j] = temp[j];
}
}
}