Merge Sort
来源:互联网 发布:现在有什么网络歌曲 编辑:程序博客网 时间:2024/05/20 01:38
The main idea of merge sort is:
- Divide array into two halves
- Recursively sort each half
Merge two half
The purpose of Merge operation is “Given two sorted sub arrays a[lo] to a[mid] and a[mid+1] to a[hi], replace the sorted subarray a[lo] to a[hi]”
So The Merger Operation is as following:
public static void merge(int[] a, int[] aux, int lo, int mid, int hi){ // a[lo ... mid] and a[mid ... hi] have been sorted for(int k=lo;k<=hi;k++){ aux[k] = a[k]; //copy all the element in a to array-aux } int i = lo; int j = mid+1; // i scans the first array, j scans the second; k scans the whole for(int k=lo;k<=hi;k++){ if(i>mid) a[k] = aux[j++]; else if(j>hi) a[k] = aux[i++]; else if(aux[j]<aux[i]) a[k] = aux[j++]; else a[k] = aux[i++]; } }
The Sort Operation is :
// This is easy to understand, sort the first half, afterwards sort the second half. At last, merge them togetherpublic void sort(int[] a, int[] aux, int lo, int hi){ if(hi <= lo) return; int mid =lo + (hi - lo) / 2; sort(a,aux,lo,mid); sort(a,aux,mid+1,hi); merge(a,aux,lo,mid,hi); }
Test case:
public class sort { public static void main(String[] args){ int[] a = {1,9,5,7,3,0,6,2,4,13,16,15}; int[] aux = new int[a.length]; merge m = new merge(); m.sort(a,aux,0,a.length-1); for(int i=0;i<a.length; i++){ System.out.print(a[i]+" "); } }// result: 0 1 2 3 4 5 6 7 9 13 15 16}
0 0
- Merge Sort
- Merge sort
- merge sort
- merge sort
- merge sort
- Merge Sort
- merge sort
- Merge Sort
- Merge Sort
- merge sort
- Merge Sort
- Merge sort
- Merge-sort
- Merge Sort
- Merge sort
- Merge Sort
- Merge-Sort
- merge sort
- JavaScript测量和影响性能的工具和技术
- JSON解析器jq小解
- 性能测试浅谈
- php函数封装
- 初级Makefile实战示例
- Merge Sort
- HDU 1198 Farm Irrigation
- 深度 | TensorFlow:最棒的深度学习加速器
- 进击的图表-看图学知识
- [Swift开发实战]-闭包
- 年度盘点和预测:数说汽车互联网市场
- 服务器端架构,前端服务器与客户端随机负载平衡
- linux查看进程的启动时间
- C语言 CRC32校验算法