0

鉴于此合并排序代码,我不确定如何修改代码以使用插入排序进行排序,以便我们使用插入排序将数据长度 n 划分为 k 个区间,然后使用正常的合并排序方法合并这些排序的 k 个区间。这是我的合并排序代码 public class hw4class1 extends 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;
            }
        }

    }
4

0 回答 0