归并排序

来源:互联网 发布:oracle数据库实训心得 编辑:程序博客网 时间:2024/06/07 12:06

在讲归并排序之前需要了解一个策略那就是分治法,把一个大的问题分解成一个小的问题,大问题和小问题都是同一个问题。在小问题里面去解决。
下面就是实现的代码:

public class SequenceTool {    /**     * 归并排序     * @param list 传入的数组对象     */    public static void mergeSort(int[] list){        //因为使用的是递归,那就需要有一个终止的条件,那就是list的长度等于一的时候那就停止        if(list.length > 1){            //把原数组的前一半递归            int[] firstHead = new int[list.length/2];            System.arraycopy(list, 0, firstHead, 0, list.length/2);            mergeSort(firstHead);            //把原数组的后面的递归            int secondLength = list.length-list.length/2;            int[] secondHead = new int[secondLength];            System.arraycopy(list, list.length/2, secondHead, 0, secondLength);            mergeSort(secondHead);            //把两个数组合并            int[] temp = merge(firstHead,secondHead);            System.arraycopy(temp, 0, list, 0, temp.length);        }    }    /**     * 合并两个数组     * @param first 第一个数组     * @param second 第二个数组     * @return  返回一个两个数组合并排序后的数组。     */    private static int[] merge(int[] first, int[] second) {        // TODO Auto-generated method stub        int[] temp = new int[first.length+second.length];        int count1 = 0;//表示第一个数组当前的指针        int count2 = 0;//表示第二个数组当前的指针        int count3 = 0;//表示合并后数组当前的指针        while(count1 < first.length && count2 < second.length){            if(first[count1] < second[count2]){                temp[count3++] = first[count1++];            }else{                temp[count3++] = second[count2++];            }        }        while(count1 < first.length){            temp[count3++] = first[count1++];        }        while (count2 < second.length) {            temp[count3++] = second[count2++];        }        return temp;    }}

说一些写这个代码想到的那些问题,第一个就是递归,那么递归的条件有哪些,怎么样递归。第二是两个数组之间排序然后合并成一个的问题。还有第三个问题那就是不断的把数组复制,而且使用递归那也会有点性能问题,不过在这里我们不需要去关心的,效率才是我们要关心的。由于之前学算法的时候没有好好听老师讲递归算法的时间复杂度,所以这里就不说怎么算时间复杂度了。今天就到这里,有什么问题可以评论,大家一起学习进步。谢谢

0 0