Manipulating Merge-Sort

75 views Asked by At

How would I go about manipulating mergesortso that it sorts each pair of numbers by the sum of their square?

For example my array has the numbers {2,7,1,4}. Being that 2^2 + 7^2 > 1^2 + 4^2 after running mergesort on the array I want {1,4,2,7}.

The question I was given was how to sort coordinates with regards to their distance from axis origins in O(nlogn) time.

void merge(int arr[], int left, int middle, int right)
{
    int i, j, k;
    int n1 = middle - left + 1;
    int n2 =  right - middle;

    int L[n1], R[n2];

    for(i = 0; i < n1; i++)
        L[i] = arr[left + i];

    for(j = 0; j < n2; j++)
        R[j] = arr[middle + 1+ j];

    i = 0;
    j = 0;
    k = left;
    while (i < n1 && j < n2){
        if (L[i] <= R[j]){
            arr[k] = L[i];
            i++;
        } else {
            arr[k] = R[j];
            j++;
        }
        k++;
    }

    while (i < n1) {
        arr[k] = L[i];
        i++;
        k++;
    }

    while (j < n2) {
        arr[k] = R[j];
        j++;
        k++;
    }
}

void mergeSort(int arr[], int left, int right)
{
    if (left < right){
        int middle = left+(right-left)/2; 
        mergeSort(arr, left, middle);
        mergeSort(arr, middle+1, right);
        merge(arr, left, middle, right);
    }
}

Is this a good strategy? Or should I be using quicksort?

0

There are 0 answers