zoukankan      html  css  js  c++  java
  • [转]归并排序

    (java版)

    public class mergingSort {

    public static void merge(int[] a,int left, int center, int right){
    int[] tmpArr = new int[a.length];
    int mid = center + 1;
    int third = left;
    //third记录中间数组的索引
    int tmp = left;
    while(left <= center && mid <= right){
    //从两个数组中取出最小的放入中间数组
    if(a[left] <= a[mid]){
    tmpArr[third++] = a[left++];
    }else{
    tmpArr[third++] = a[mid++];
    }
    }
    //剩余部分一次放入中间数组
    while(mid <= right){
    tmpArr[third++] = a[mid++];
    }
    while(left <= center){
    tmpArr[third++] = a[left++];
    }
    //将中间数组中的内容复制灰原数组
    while(tmp <= right){
    a[tmp] = tmpArr[tmp++];
    }
    }

    public static void sort(int[] a, int left, int right){
    if(left < right){
    //找出中间索引
    int center = (left + right)/2;
    //对左边数组进行递归
    sort(a,left,center);
    //对右边数组进行递归
    sort(a,center+1,right);
    //合并
    merge(a,left,center,right);
    }
    }
    public static void main(String[] args) {
    int[] a = {0,2,5,43,32,65,43,21,87,1};
    sort(a,0,a.length-1);
    for(int i =0; i<a.length; i++)
    System.out.print(a[i]+" ");
    }

    }

  • 相关阅读:
    config Doku wiki
    [转载]【python】ipython与python的区别
    数组和指针
    C++初始化数据成员
    RSA算法原理
    C++四种cast
    百度笔试准备2
    百度笔试准备1
    百度面试准备
    C++的空类中默认产生哪些类成员函数
  • 原文地址:https://www.cnblogs.com/tangtang-123/p/4436045.html
Copyright © 2011-2022 走看看