首页 > 代码库 > Merge Sort
Merge Sort
public class Solution { /** * @param A an integer array * @return void */ public void sortIntegers2(int[] A) { // Write your code here if (A == null || A.length == 0) { return; } int[] tmp = new int[A.length]; mergeSort(A, 0, A.length - 1, tmp); } private void mergeSort(int[] A, int start, int end, int[] tmp){ if (start >= end) { return; } int mid = start + (end - start) / 2; mergeSort(A, start, mid, tmp); mergeSort(A, mid + 1, end, tmp); merge(A, start, mid, end, tmp); } private void merge(int[] A, int start, int mid, int end, int[] tmp) { int left = start; int right = mid + 1; int index = start; while (left <= mid && right <= end) { if (A[left] < A[right]) { tmp[index++] = A[left++]; } else { tmp[index++] = A[right++]; } } while (left <= mid) { tmp[index++] = A[left++]; } while (right <= end) { tmp[index++] = A[right++]; } for (int i = start; i <= end; i++) { A[i] = tmp[i]; } } }
Merge Sort
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。