Ask Question
20 January, 05:15

I have six nuts and six bolts. Exactly one nut goes with each bolt. The nuts are all different sizes, but it's hard to compare them to each other. (Same for the bolts.) But if I try a nut and a bolt together, it's easy to see if the nut is smaller than, the same size as, or larger than the bolt. Find a way to use quicksort to match up the nuts and bolts.

+3
Answers (1)
  1. 20 January, 05:23
    0
    In order to arrange the corresponding nuts and bolts in order using quicksort algorithm, we need to first create two arrays, one for nuts and another for bolts namely nutsArr[6] and boltsArr[6]. Now, using one of the bolts as pivot, we can rearrange the nuts in the nuts array such that the nuts on left side of the element chosen (i. e, the ith element indexed as nutArr[i]) are smaller than the nut at ith position and nuts to the right side of nutsArr[i] are larger than the nut at position "I". We implement this strategy recursively to sort the nuts array. The reason that we need to use bolts for sorting nuts is that nuts are not comparable among themselves and bolts are not comparable among themselves (as mentioned in the question)

    The pseudocode for the given problem goes as follows:

    / / method to quick sort the elements in the two arrays

    quickSort (nutsArr[start ... end], boltsArr[start ... end]) : if start < end: / / choose a nut from nutsArr at random randElement = nutsArr[random (start, end+1) ] / / partition the boltsArr using the randElement random pivot pivot = partition (boltsArr[start ... end], randElement) / / partition nutsArr around the bolt at the pivot position partition (nutsArr[start ... end], boltsArr[pivot]) / / call quickSort by passing first partition quickSort (nutsArr[start ... pivot-1], boltsArr[start ... pivot-1]) / / call quickSort by passing second partition quickSort (nutsArr[pivot+1 ... end], boltsArr[pivot+1 ... end])

    / / method to partition the array passed as parameter, it also takes pivot as parameter

    partition (character array, integer start, integer end, character pivot)

    {

    integer i = start;

    loop from j = start to j < end

    {

    check if array[j] < pivot

    {

    swap (array[i], array[j])

    increase i by 1;

    }

    else check if array[j] = pivot

    {

    swap (array[end], array[j])

    decrease i by 1;

    }

    }

    swap (array[i], array[end])

    return partition index i;

    }
Know the Answer?
Not Sure About the Answer?
Find an answer to your question ✅ “I have six nuts and six bolts. Exactly one nut goes with each bolt. The nuts are all different sizes, but it's hard to compare them to each ...” in 📘 Computers and Technology if you're in doubt about the correctness of the answers or there's no answer, then try to use the smart search and find answers to the similar questions.
Search for Other Answers