static method不需要 object来调用;object free;每个obj都可以改一下它-,- global scope public class MergeSort {//class public int[] mergeSort(int[]array) {// class里面都public mergesort方法, //给一个数组,然后排好序后 把reference返回给你~ //check null array first if(array == null) { return array; } //allocate helper array to help merge step. //so that we guarantee no more than O(n)in this case. 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 left,int mid,int right) { //copy the content to helper array and we will merge from the helper array for (int i = left; i <= right; i++) { helper = array; } 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 [leftInde++]; } // if there are some elements at right side, we do not to copy them because they are already in the position/ public static void main (String[] args){ int[]array = {3,5,1,6,2}; MergeSort sorter = new MergeSort();//new 一个对象出来; array = sorter.mergeSort(array);//然后我门在对象sorter上边来call方法;
|