HackerRank: Permuting Two Arrays Program in C

There are two n-element arrays of integers, A and B. Permute them into some A’ and B’ such that the relation A'[i]+B'[i]>=k holds for all i where 0<=i and i>=n.

void swap(int *xp, int *yp)
{
    int temp = *xp;
    *xp = *yp;
    *yp = temp;
}

void selectionSort_a(int arr[], int n)
{
    int i, j, min_idx;
 
    // One by one move boundary of unsorted subarray
    for (i = 0; i < n-1; i++)
    {
        // Find the minimum element in unsorted array
        min_idx = i;
        for (j = i+1; j < n; j++)
          if (arr[j] < arr[min_idx])
            min_idx = j;
 
        // Swap the found minimum element with the first element
        swap(&arr[min_idx], &arr[i]);
    }
}

void selectionSort_d(int arr[], int n)
{
    int i, j, min_idx;
 
    // One by one move boundary of unsorted subarray
    for (i = 0; i < n-1; i++)
    {
        // Find the minimum element in unsorted array
        min_idx = i;
        for (j = i+1; j < n; j++)
          if (arr[j] > arr[min_idx])
            min_idx = j;
 
        // Swap the found minimum element with the first element
        swap(&arr[min_idx], &arr[i]);
    }
}
char* twoArrays(int k, int A_count, int* A, int B_count, int* B) {
    static char str1[] = "YES";
    static char str2[] = "NO";
    selectionSort_a(A, A_count);
    selectionSort_d(B, B_count);
    for(int i=0; i<A_count; i++){
        if(A[i]+B[i] <k) return str2;
        
    }
    return str1;
}

Leave a Comment