[算法基础]归并排序

来源:互联网 发布:淘宝最好的饰品店 编辑:程序博客网 时间:2024/05/17 02:49

归并排序即将目标数组分成N个最小的组(相邻的2个数字),并将这些最小子数组排序,依次合并相邻的子数组,最后各自有序的子数组将会合并成完全有序的数组。

这将需要用到递归思想。

java实现

static class MergeSort{        static void sort(int[] a, int start, int end){            int mid = (start + end) / 2;            //说明已经分解到最小的组            if(start >=end) return;            sort(a, start, mid); //继续分解上半段            sort(a, mid + 1, end); //分解下半段            merge(a, start, mid, end); //合并        }        private static void merge(int[] a, int start, int firstEnd, int secondEnd){            int index1 = start, index2 = firstEnd + 1;            int len = secondEnd - start + 1;            int[] tmp = new int[len]; //临时数组,用于存放排好序的数字            int tmpIndex = 0;            while(index1 <= firstEnd && index2 <= secondEnd){                if(a[index1] <= a[index2]){ //逐个对比2个子数组的元素,小的优先放到tmp数组中                    tmp[tmpIndex++] = a[index1++];                }                else {                    tmp[tmpIndex++] = a[index2++];                }            }            //其中一个子数组已经遍历完成,那么将另一个子数组中剩下的元素也插入到tmp            while(index1 <= firstEnd) {                tmp[tmpIndex++] = a[index1++];            }            while(index2 <= secondEnd)  {                tmp[tmpIndex++] = a[index2++];            }            for(int i = 0;i<len;i++){ //将tmp数组覆盖目标数组对应的部分                a[start++] = tmp[i];            }        }    }

效率对比

最后使用随机生成的数组来测试下快速排序、冒泡排序、选择排序和归并排序的效率。

长度为25000的数组:
快排和归并还是很快的。

quickSort time:9bubbleSort time:1231selectionSort time:170MergeSort time:10

长度为50000的数组:
快排和归并依然保持在两位数的时间。

quickSort time :20bubbleSort time :4705selectionSort time :676MergeSort time :16

长度为150000的数组:
看到快排和归并排序的优势已经完全显现了。

quickSort time :44bubbleSort time :39902selectionSort time :5766MergeSort time :29
原创粉丝点击