java排序--归并排序
来源:互联网 发布:南京八大碗网络怎么样 编辑:程序博客网 时间:2024/04/29 19:30
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];
}
}
}
- java排序--归并排序
- 排序-归并排序-Java
- Java排序算法 归并排序
- Java 排序之 归并排序
- java排序算法---归并排序
- 归并排序(Java) @排序
- Java排序算法:归并排序
- Java排序五:归并排序
- JAVA排序算法---归并排序
- 排序中的归并排序Java
- java排序之归并排序
- Java 快速排序 归并排序
- Java排序算法--归并排序
- Java 排序算法-归并排序
- Java排序之归并排序
- java排序之 --- 归并排序
- 归并排序Java实现
- java归并排序算法
- 当人体器官还不能作为普及的身份识别工具时
- 解决ubuntu中vi不能正常使用方向键与退格键的问题
- 做更好的自己 1/4/2014
- Linux下Socket编程
- Centos添加字体
- java排序--归并排序
- robotium重签名问题
- 用Texture Packer打包数据
- JAVA SE---基础(1)
- OD修改窗口标题栏
- window下Objective-C 2.0 集成开发环境 Clang编译器版本
- 算法:低位优先(LSD)
- 2014年十大消费者趋势
- 数字三角形