- 马上要实习面试了,总结和分析一下算法与数据结构。
归并排序先使每个子序列有序,再使子序列段间有序。最后将两个有序表合并成一个有序表。
时间复杂度为O(nlogn)。
public static void MergeSort
(int[]arr,int left, int right,int[]temp){
if(left<right){
int mid=(left+right)/2;
MergeSort(arr,left,mid,temp);
MergeSort(arr,mid+1,right,temp);
merge(arr,left,mid,right,temp);
}
}
public static void merge
(int[]arr,int left,int mid,int right,int[]temp){
int l =left;
int r= mid+1;
int t=0;
while(l<=mid&&r<=right){
if(arr[l]<arr[r]){
temp[t]=arr[l]
l++;
}else{
temp[t]=arr[r];
r++;
}
t++;
}
while(l<=mid){
temp[t]=arr[l];
l++;
t++;
}
while(r<=right){
temp[t]=arr[r];
r++;
t++;
}
t=0;
int tempLeft = left;
while(tempLeft<=right){
arr[tempLeft]=temp[t];
tempLeft++;
t++;
}
}