修改以合并排序以使用插入排序进行排序,然后正常合并

时间:2013-10-25 19:27:30

标签: java sorting mergesort

鉴于此合并排序代码,我不确定如何修改代码以使用插入排序进行排序,以便我们将数据长度n除以插入排序的k个区间,然后将这些排序的k区间与常规合并排序方法合并。 这是我的合并排序代码 公共类hw4class1扩展了Sorter {

public static void printArray(int[] array) {
            if (array.length <= 100) {
                for(int i=0; i < array.length; ++i) {
                    System.out.print(array[i]+" "); // print out values
                }
                System.out.println();
            } else {
                System.out.println("array too large to print ("+array.length+" elements).");
            }

        }

        public void sort(int[] values) {
        System.out.print("call to "+this.getClass().getName()+" with ");
            printArray(values);
            if (values==null || values.length <=1) { // check for termination condition
                System.out.print("returning from "+this.getClass().getName()+" with ");
                printArray(values);
                return;
            } else {
                int middle = values.length/2; // divide array into two arrays of half size
                int[] left = new int[middle];
                for (int i=0; i<middle; i++) {
                    left[i] = values[i];
                }
                int[] right = new int[values.length-middle];
                for (int i=0; i<values.length-middle; i++) {
                    right[i] = values[middle+i];
                }
                sort(left); // recursively call sorting function on each smaller arry
                sort(right);

                int l=0, r=0; // combine sorted arrays
                for (int i=0; i<values.length; i++) {
                    if (r>=right.length || (l<left.length && left[l]<right[r])) {
                        values[i]=left[l];
                        l++;
                    } else {
                        values[i]=right[r];
                        r++;
                    }
                }
                System.out.print("returning from "+this.getClass().getName()+" with ");
            printArray(values);
                return;
            }
        }

    }

0 个答案:

没有答案