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]+" ");
    }

    }

  • 相关阅读:
    Hello, Fedora.
    Android与Linux分道扬镳
    VIM教程V1.5梁昌泰
    强大的NTFS文件系统
    Linux下的cc与gcc
    g++与gcc的区别
    Fedora下解压缩的相关问题
    The GNU C Reference Manual
    Linux Kbuild文档
    实验一:计算机是怎样工作的
  • 原文地址:https://www.cnblogs.com/tangtang-123/p/4436045.html
Copyright © 2011-2022 走看看