public class MergeSort {
private long[] arr;
private int size;
private int index;
public MergeSort(){}
public MergeSort(int size){
this.size = size;
this.arr = new long[size];
}
public void insert(long val){
if(this.index < this.size)
this.arr[this.index++] = val;
else
System.out.println("Array already full! value:"+val);
}
public void mergeSort1(){
long[] temp = new long[this.size];
this.recMergeSort(temp,0,this.size-1);
}
public void recMergeSort(long[] arr,int low,int high){
if(low == high){
return;
}else{
int mid = (low+high)/2;
this.recMergeSort(arr, low, mid);
this.recMergeSort(arr, mid+1, high);
this.merge(arr, low, mid+1, high);
}
}
public void merge(long[] arr,int low,int high,int upperBound){
int current = 0;
int lowerIndex = low;
int middleIndex = high-1;
int n = upperBound-low+1;
while(low <= middleIndex && high <= upperBound){
if(this.arr[low] < this.arr[high]){
arr[current++] = this.arr[low++];
}else{
arr[current++] = this.arr[high++];
}
}
while(low <= middleIndex){
arr[current++] = this.arr[low++];
}
while(high <= upperBound){
arr[current++] = this.arr[high++];
}
for(current=0; current<n; current++){
this.arr[lowerIndex+current] = arr[current];
}
}
public void display(){
for(long l : this.arr){
System.out.print(l+" ");
}
System.out.println("");
}
public static void main(String[] args){
MergeSort ms = new MergeSort(12);
ms.insert(11);
ms.insert(23);
ms.insert(55);
ms.insert(1);
ms.insert(8);
ms.insert(12);
ms.insert(54);
ms.insert(66);
ms.insert(85);
ms.insert(39);
ms.insert(391);
ms.insert(139);
ms.display();
System.out.println("");
ms.mergeSort1();
ms.display();
}
}
归并排序
最新推荐文章于 2025-05-01 20:06:47 发布