Search code examples
javamergesortdivide-and-conquer

Sorting index of array using merge Sort


I was trying to sort the index of an array using mergesort. The mergesort works perfectly , and the final answer is exactly correct but I am not sure why the indexes do not work out in correct positions. I do not want to sort the array, all I want to do is sort the perm[] array which is the index list.

To avoid confusions, Heres an example: perm array holds the initial indices of the original array nums[] (i.e. 0 to nums.length - 1)

I want to move the indices in the perm array based on the data in the nums[] array such that the indices represent the sorted order.

For example :
Array -> (-1,9,-5,3,0)
Initial perm -> (0,1,2,3,4)
After sorting perm based on array - > (2,0,4,3,1)

Here's my code:

import java.util.Arrays;

public class IndexSort {

    public boolean leq(Comparable u, Comparable v) {
        return u.compareTo(v) <= 0;
    }

    public void merge(Comparable a[], int temp[], int perm[], int lo, int mid, int hi) {
        int i = lo, j = mid + 1;

        for (int k = lo; k <= hi; k++) {
            temp[k] = perm[k];
        }

        for (int k = lo; k <= hi; k++) {
            if (i > mid) {
                perm[k] = temp[j++];
            } else if (j > hi) {
                perm[k] = temp[i++];
            } else if (leq(a[perm[i]], a[perm[j]])) {
                perm[k] = temp[i++];
            } else {
                perm[k] = temp[j++];
            }
        }
    }

    public void mergeSort(Comparable a[], int temp[], int perm[], int lo, int hi) {
        if (hi <= lo)
            return;
        int mid = (hi + lo) / 2;
        mergeSort(a, temp, perm, lo, mid);
        mergeSort(a, temp, perm, mid + 1, hi);
        merge(a, temp, perm, lo, mid, hi);
        System.out.println(" lo  = " + lo + "  mid  = " + mid + "  hi  = " + hi);
        System.out.println(Arrays.toString(perm));
    }

    public void indexSort(Comparable nums[], int perm[]) {
        int temp[] = new int[nums.length];
        Comparable temp2[] = new Comparable[nums.length];
        mergeSort(nums, temp, perm, 0, nums.length - 1);
    }

    public static void main(String[] args) {
        IndexSort o1 = new IndexSort();
        Comparable nums[] = { 12, -12, 0, 123, -123, 1, 2, 3, 4, -4, -4, -3, -2, 1 };
        int perm[] = new int[nums.length];
        for (int i = 0; i < perm.length; i++) {
            perm[i] = i;
        }
        System.out.println(Arrays.toString(nums));
        System.out.println(Arrays.toString(perm));
        o1.indexSort(nums, perm);
        System.out.println(Arrays.toString(perm));
    }
}

Solution

  • I think this line needs to change from perm to temp:

    } else if (leq(a[temp[i]], a[temp[j]])) {