merge sort
merge sort https://www.youtube.com/watch?v=iMT7gTPpaqw // time : nlogn // space: n // n : the number of elements in the array public class MergeSort{ public int[] mergeSort(int[] array){ if(array == null){ return array; } int[] helper = new int[array.length]; mergeSort(array, helper, 0, array.length - 1); return array; } private void mergeSort(int[] array, int[] helper, int left, int right){ if(left >= right){ return; } int mid = left + (right - left) / 2; mergeSort(array, helper, left, mid); mergeSort(array, helper, mid + 1, right); merge(array, helper, left, mid, right); } private void merge(int[] array, int[] helper, int mid, int left, int right){ // copy the content to helper array and we will merge from the helper array for(int i = 0; i <= right; i++){ helper[i] = array[i]; } int leftIndex = left; int rightIndex = mid + 1; while(leftIndex <= mid && rightIndex <= right){ if(helper[leftIndex] <= helper[rightIndex]){ array[left++] = helper[leftIndex++]; }else{ array[left++] = helper[rightIndex++]; } } // if we still have some elements at left side, we need to copy them while(leftIndex <= mid){ array[left++] = helper[leftIndex++]; } // if there are some elements at right side, we dont need to copy them because // they are already in their position } } // testing public static void main(String[] args){ MergeSort solution = new MergeSort(); int[] array = null; array = solution.mergeSort(array); System.out.println(Arrays.toString(array)); array = new int[0]; array = solution.mergeSort(array); System.out.println(Arrays.toString(array)); array = new int[] {4,3,5,7,1}; array = solution.mergeSort(array); System.out.println(Arrays.toString(array)); }
posted on 2018-08-09 18:44 猪猪🐷 阅读(124) 评论(0) 收藏 举报
浙公网安备 33010602011771号