Non-recursive merge sort with two nested loops - how?

前端 未结 4 1498
被撕碎了的回忆
被撕碎了的回忆 2021-02-04 12:24

First question here, and yes this is a homework question. We are tasked with performing merge sort on an array (which I am familiar with), but in a way I am unsure of how to do.

4条回答
  •  無奈伤痛
    2021-02-04 12:31

    Here is the Java Implementation

    public static > void iterativeMergeSort(T[] seed) {
    
        for (int i = 1; i >  void inPlaceMerge(T[] collection, int low, int mid, int high) {
        int left = low;
        int right = mid + 1;
    
        if(collection[mid].equals(collection[right])) {
            return ;//Skip the merge if required
        }
        while (left <= mid && right <= high) {          
            // Select from left:  no change, just advance left
            if (collection[left].compareTo(collection[right]) <= 0) {
                left ++;
            } else { // Select from right:  rotate [left..right] and correct
                T tmp = collection[right]; // Will move to [left]
                rotateRight(collection, left, right - left);
                collection[left] = tmp;
                // EVERYTHING has moved up by one
                left ++; right ++; mid ++;
            }
        }       
    }
    

    Here is the Unit Test private Integer[] seed;

    @Before
    public void doBeforeEachTestCase() {
        this.seed = new Integer[]{4,2,3,1,5,8,7,6};
    }
    @Test
    public void iterativeMergeSortFirstTest() {
        ArrayUtils.iterativeMergeSort(seed);
        Integer[] result = new Integer[]{1,2,3,4,5,6,7,8};
        assertThat(seed, equalTo(result));  
    }
    

提交回复
热议问题