Java-归并排序

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];
        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
归并排序是一种常见的排序算法,它采用分治的思想,将一个大问题分解为多个小问题进行解决,最后将结果合并得到最终的排序结果。下面是Java中使用归并排序的示例代码: ```java public class MergeSort { public static void mergeSort(int[] arr) { if (arr == null || arr.length <= 1) { return; } int[] temp = new int[arr.length]; mergeSort(arr, 0, arr.length - 1, temp); } private 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); // 合并左右两部分 } } private static void merge(int[] arr, int left, int mid, int right, int[] temp) { int i = left; // 左序列指针 int j = mid + 1; // 右序列指针 int t = 0; // 临时数组指针 while (i <= mid && j <= right) { if (arr[i] <= arr[j]) { temp[t++] = arr[i++]; } else { temp[t++] = arr[j++]; } } while (i <= mid) { // 将左边剩余元素填充进temp中 temp[t++] = arr[i++]; } while (j <= right) { // 将右序列剩余元素填充进temp中 temp[t++] = arr[j++]; } t = 0; // 将temp中的元素全部拷贝到原数组中 while (left <= right) { arr[left++] = temp[t++]; } } } ``` 使用归并排序时,可以调用`mergeSort`方法传入待排序的数组即可完成排序。在`mergeSort`方法中,首先判断数组是否为空或长度小于等于1,如果是,则直接返回。然后创建一个临时数组`temp`,并调用`mergeSort`方法进行递归排序。在递归排序的过程中,将数组分为左右两部分,分别对左右两部分进行归并排序,最后调用`merge`方法将左右两部分合并起来。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值