Java-归并排序
来源:互联网 发布:网络发帖推广 编辑:程序博客网 时间:2024/05/29 13:56
public void mergeSort(int[] a, int first, int last, int[] temp){
if(first<last){
int mid = (first+last)/2;
mergeSort(a,first,mid,temp); //左边有序
mergeSort(a,mid+1,last,temp); //右边有序
//把相邻两个有序的数组合并,形成一个新的有序数组
mergeArray(a,first,mid,last,temp);
}
}
private void mergeArray(int[] a, int first, int mid, int last, int[] temp) {
int i=first,m=mid;
int j=mid+1,n=last;
int count = 0;//记录这次合并了几个数
while(i<=m && j<=n){
if(a[i] <=a[j]){
temp[count++] = a[i++];
} else{
temp[count++] = a[j++];
}
}
while(i<=m){
temp[count++] = a[i++];
}
while(j<=n){
temp[count++] = a[j++];
}
//把临时数组排好序的部分拷贝回原始数组
for(int k=0; k<count; k++){
a[first+k] = temp[k];
}
}
if(first<last){
int mid = (first+last)/2;
mergeSort(a,first,mid,temp); //左边有序
mergeSort(a,mid+1,last,temp); //右边有序
//把相邻两个有序的数组合并,形成一个新的有序数组
mergeArray(a,first,mid,last,temp);
}
}
private void mergeArray(int[] a, int first, int mid, int last, int[] temp) {
int i=first,m=mid;
int j=mid+1,n=last;
int count = 0;//记录这次合并了几个数
while(i<=m && j<=n){
if(a[i] <=a[j]){
temp[count++] = a[i++];
} else{
temp[count++] = a[j++];
}
}
while(i<=m){
temp[count++] = a[i++];
}
while(j<=n){
temp[count++] = a[j++];
}
//把临时数组排好序的部分拷贝回原始数组
for(int k=0; k<count; k++){
a[first+k] = temp[k];
}
}
0 0
- java排序--归并排序
- 排序-归并排序-Java
- 归并排序Java实现
- java归并排序算法
- JAVA归并排序算法
- java归并排序
- java归并排序
- Java实现归并排序
- 归并排序(java)
- 25、JAVA归并排序
- java 归并排序
- java归并排序
- Java归并排序
- 归并排序 java
- Java实现归并排序
- 归并排序Java实现
- java 归并排序
- Java归并排序
- สนุกกับการเล่น ibcbet ผ่านช่องทางของมือถือ
- 玩转iOS开发 - 多线程开发
- Horizontal---ProgressBar
- Python基础:17类和实例之一
- <c:forEach varStatus="status">中 varStatus的属性简介
- Java-归并排序
- x86和arm对于锁实现的差异
- runtime之forwardInvocation
- mybatis多长查询缓存问题
- python去除matlab文件中的空行
- Shader Model知识点
- webview与如何利用DisplayMetrics获取屏幕高度和宽度
- vector操作
- file_put_contents之用途