public class MergeSort {
/**
* 方式一
*/
public static <E extends Comparable<E>> void sort(E[] arr){
sort(arr,0,arr.length-1);
}
// 前闭后闭
private static <E extends Comparable<E>> void sort(E[] arr, int l, int r) {
if(l >= r){
return;
}
int mid = l + (r - l)/2;
sort(arr,l,mid);
sort(arr,mid + 1,r);
if(arr[mid].compareTo(arr[mid+1]) > 0){
merge(arr,l,mid,r);
}
}
private static <E extends Comparable<E>> void merge(E[] arr, int l, int mid, int r) {
// 前闭后开
E[] temp = Arrays.copyOfRange(arr,l,r + 1);
int i = l,j = mid + 1;
for (int k = l; k <= r; k++) {
if(i > mid){
arr[k] = temp[j-l];j++;
}else if(j > r){
arr[k] = temp[i-l];i++;
}else if(temp[i-l].compareTo(temp[j-l]) <= 0){
arr[k] = temp[i-l];i++;
}else{
arr[k] = temp[j-l];j++;
}
}
}
/**
* 方式二
*/
public static <E extends Comparable<E>> void sort2(E[] arr){
E[] temp = Arrays.copyOf(arr,arr.length);
sort2(arr,0,arr.length-1,temp);
}
private static <E extends Comparable<E>> void sort2(E[] arr, int l, int r,E[] temp) {
if(l >= r){
return;
}
int mid = l + (r - l)/2;
sort2(arr,l,mid,temp);
sort2(arr,mid + 1,r,temp);
if(arr[mid].compareTo(arr[mid+1]) > 0){
merge2(arr,l,mid,r,temp);
}
}
private static <E extends Comparable<E>> void merge2(E[] arr, int l, int mid, int r,E[] temp) {
System.arraycopy(arr,l,temp,l,r - l + 1);
int i = l,j = mid + 1;
for (int k = l; k <= r; k++) {
if(i > mid){
arr[k] = temp[j];j++;
}else if(j > r){
arr[k] = temp[i];i++;
}else if(temp[i].compareTo(temp[j]) <= 0){
arr[k] = temp[i];i++;
}else{
arr[k] = temp[j];j++;
}
}
}
/**
* 方式三
*/
public static <E extends Comparable<E>> void sort3(E[] arr){
E[] temp = Arrays.copyOf(arr,arr.length);
int n = arr.length;
for (int sz = 1; sz < n; sz += sz) {
for (int i = 0; i + sz < n; i += sz + sz) {
// (arr,i,i + sz - 1,i + sz + sz - 1,temp);
merge2(arr,i,i + sz - 1,Math.min(i + sz + sz - 1,n-1),temp);
}
}
}
public static void main(String[] args) {
Integer[] arr = {98,88,78,56,66,3,6,2,1,8};
System.out.println(Arrays.toString(arr));
MergeSort.sort3(arr);
System.out.println(Arrays.toString(arr));
}
}
算法与数据结构——归并排序
最新推荐文章于 2024-11-12 12:29:51 发布