Question

In: Computer Science

from partition import partition def quicksort(a: list, l: int, u: int) -> None: '''Sort the given...

from partition import partition

def quicksort(a: list, l: int, u: int) -> None:
  '''Sort the given list a in non-descending order.
  Precondition: 0 <= l and u < len(a)'''

  if l < u:
    mid = (l + u) // 2
    three = [a[l], a[mid], a[u]]
    three.sort()
    if three[1] == a[l]:
      pivot_loc = l
    elif three[1] == a[u]:
      pivot_loc = u
    else:
      pivot_loc = mid
    a[u], a[pivot_loc] = a[pivot_loc], a[u]
    pivot = a[u]    
    i = partition(a, l, u - 1, pivot)
    a[i], a[u] = a[u], a[i]
    quicksort(a, l, i - 1)
    quicksort(a, i + 1, u)
from typing import List, Any, Tuple

def partition (a: List, l: int, u: int, pivot: Any) -> Tuple[int, int]:
  """
  Alternate partition: This new partition procedure maintains two
  split points, dividing the list into those elements that are smaller
  than the pivot, those exactly equal to the pivot, and those strictly
  larger than the pivot. Return a tuple of the indices of the two split points.

  >>> l = [-19, 1, 1, 1, 18, 18, 104, 418]
  >>> partition(l, 0, len(l)-1, 18)
  (4, 6)
  >>> l
  [-19, 1, 1, 1, 18, 18, 418, 104]
  """
  
  i = l
  j = l
  k = u
  while j <= k:
    if a[j] < pivot:
      a[i], a[j] = a[j], a[i]
      i += 1
      j += 1
    elif a[j] == pivot:
      j += 1
    else:
      a[j], a[k] = a[k], a[j]
      k -= 1
  return (i, j)

Q.The quicksort has some mistakes.Modify the quicksort according to the partition function given below.

Solutions

Expert Solution

Program code to copy

from partition import partition



def quicksort(a: list, l: int, u: int) -> None:

    '''Sort the given list a in non-descending order.

    Precondition: 0 <= l and u < len(a)'''



    if l < u:

        mid = (l + u) // 2

        three = [a[l], a[mid], a[u]]

        three.sort()



        ''''

        Searching for appropriate pivot location. 

        '''

        if three[1] == a[l]:

            pivot_loc = l

        elif three[1] == a[u]:

            pivot_loc = u

        else:

            pivot_loc = mid


        ''''

             I have commented below line which was in actual question 

             as it not required to change value pivot location which 

             is already determined. 

        '''

        # a[u], a[pivot_loc] = a[pivot_loc], a[u]


        pivot = a[pivot_loc]

        #Two variables are required to hold two return values of function

        i, mid = partition(a, l, u , pivot)



        ''''

            Interchanging these value was defeating purpose of Sorting.  

        '''

        # a[i], a[u] = a[u], a[i]



        if (i+1)!=mid:

            quicksort(a, l, i - 1)

            #function call is changed according to two returned partitioned values.

            quicksort(a, mid+1, u)

        else:

            #To handle the case without any duplicate value

            quicksort(a, l, i - 1)

            quicksort(a, mid , u)







print("Input Array:", end = " ")

l =   [-1, 13, 1, 89, 18, 15, 104, 500]

print(l)



print("Output Array:", end = " ")

quicksort(l, 0, len(l)-1)

print(l)

NO change in partition function. Keep Partition.py in same directory to import.

Partition.py has the same code as in question.

Program Screenshot

Program Output

Considering different input cases


Related Solutions

def change_type(info: List[list]) -> None: """ Modify info to a float if and only if it...
def change_type(info: List[list]) -> None: """ Modify info to a float if and only if it represents a number that is not a whole number(a float), and convert info to an int if and only if it represents a whole number, keep everythingelse as a string. >>> i = [['apple', '888', 'School', '111.1']] >>> change_type(i) >>> i   [['apple', 888, 'School', '111.1']] Please help! Write as little code as possible! Please only use if statements, nested loop and lists to solve...
def warmer_year(temps_then: List[int], temps_now: List[int]) -> List[str]: """Return a list of strings representing whether this year's...
def warmer_year(temps_then: List[int], temps_now: List[int]) -> List[str]: """Return a list of strings representing whether this year's temperatures from temps_now are warmer than past temperatures in temps_then. The resulting list should contain "Warmer" at the indexes where this year's temperature is warmer, and "Not Warmer" at the indexes where the past year was warmer, or there is a tie. Precondition: len(temps_then) == len(temps_now) >>> warmer_year([10], [11]) ['Warmer'] >>> warmer_year([26, 27, 27, 28], [25, 28, 27, 30]) ['Not Warmer', 'Warmer', 'Not Warmer',...
Try to debug it! ######################################## ##def rev_list_buggy(L): ## """ ## input: L, a list ## Modifies...
Try to debug it! ######################################## ##def rev_list_buggy(L): ## """ ## input: L, a list ## Modifies L such that its elements are in reverse order ## returns: nothing ## """ ## for i in range(len(L)): ## j = len(L) - i ## L[i] = temp ## L[i] = L[j] ## L[j] = L[i] # ## FIXES: -------------------------- ## temp unknown ## list index out of range -> sub 1 to j ## get same list back -> iterate only over...
1a)Use the Lomuto's quicksort algorithm to sort the following list of integers in nondecreasing order for...
1a)Use the Lomuto's quicksort algorithm to sort the following list of integers in nondecreasing order for the first pivot item. Use pointers i and j for swapping items (if necessary) for each step leading to your answer. Note do the problem just for the first pivot item. 123,34,189,56,150,12,9,24 1b)Use the same list of numbers and use the Hoare's quicksort algorithm using pointers l and r and updating the pointers i and j and swapping items. Do the problem just for...
C++ Given 2 int arrays that are related, sort them correspondingly. EXAMPLE: int arr1[] = {84,...
C++ Given 2 int arrays that are related, sort them correspondingly. EXAMPLE: int arr1[] = {84, 4, 30, 66, 15}; int arr2[] = {7, 5, 2, 9, 10}; SORTED ANSWER: 4 - 5 15 - 10 30 - 2 66 - 9 84 - 7 IN C++
PYTHON PROBLEM: TASKED TO FIND THE FLAW WITH THE FOLLOWING CODE: from itertools import count def...
PYTHON PROBLEM: TASKED TO FIND THE FLAW WITH THE FOLLOWING CODE: from itertools import count def take_e(n, gen):     return [elem for (i, elem) in enumerate(gen) if i < n] def take_zc(n, gen):     return [elem for (i, elem) in zip(count(), gen) if i < n] FIBONACCI UNBOUNDED: def fibonacci_unbounded():     """     Unbounded Fibonacci numbers generator     """     (a, b) = (0, 1)     while True:         # return a         yield a         (a, b) = (b, a + b) SUPPOSED TO RUN THIS TO ASSIST WITH...
from MyStack import MyStack def infixToPostfix(infixexpr):    prec = {}    prec["*"] = 3    prec["/"] = 3    prec["+"]...
from MyStack import MyStack def infixToPostfix(infixexpr):    prec = {}    prec["*"] = 3    prec["/"] = 3    prec["+"] = 2    prec["-"] = 2    prec["("] = 1    opStack = Stack()    postfixList = []    tokenList = infixexpr.split()    for token in tokenList:        if token in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" or token in "0123456789":            postfixList.append(token)        elif token in prec:        op_2=operand_stack.peek()        operand_stack.pop()        op_1=operand_stack.peek()        operand_stack.pop()        operand_stack.push("("+op_1+token+op_2+")")    temporary_list.append(operand_stack.pop())    for i in temporary_list[0]:        infix_list.append(i)    return " ".join(infix_list) print(postfix_to_infix("3 6 7*+")) def doMath(op, op1, op2):   if op == "*":       return op1 * op2   elif...
from PIL import Image def stringToBits(string):     return str(bin(int.from_bytes(string.encode(), 'big')))[2:] def bitsToString(bits):     if bits[0:2] != '0b':         bits.
from PIL import Image def stringToBits(string):     return str(bin(int.from_bytes(string.encode(), 'big')))[2:] def bitsToString(bits):     if bits[0:2] != '0b':         bits = '0b' + bits     value = int(bits, 2)     return value.to_bytes((value.bit_length() + 7) // 8, 'big').decode() def writeMessageToRedChannel(file, message):     image = Image.open(file)     width, height = image.size     messageBits = stringToBits(message)     messageBitCounter = 0     y = 0     while y < height:         x = 0         while x < width:             r, g, b, a = image.getpixel((x, y))             print("writeMessageToRedChannel: Reading pixel %d, %d - Original values (%d, %d, %d, %d)"...
Question 1: Given the following utility function: (U=Utility, l=leisure, c=consumption) U = 2l + 3c and...
Question 1: Given the following utility function: (U=Utility, l=leisure, c=consumption) U = 2l + 3c and production function: (Y=Output, N or Ns=Labour or Labour Supply) Y = 30N1/2 If h = 100 and G =10 (h=Hours of labour, G=Government spending). Find the equilibrium levels of the real wage (w), consumption (c), leisure (l), and output (Y). Question 2: (Continuting from question 1) a, Find the relationship between total tax revenue and the tax rate if G = tWN. (G=Government spending,...
Question 1: Given the following utility function: (U=Utility, l=leisure, c=consumption) U = 2l + 3c and...
Question 1: Given the following utility function: (U=Utility, l=leisure, c=consumption) U = 2l + 3c and production function: (Y=Output, N or Ns=Labour or Labour Supply) Y = 30N1/2 If h = 100 and G =10 (h=Hours of labour, G=Government spending). Find the equilibrium levels of the real wage (w), consumption (c), leisure (l), and output (Y). Question 2: (Continuting from question 1) a, Find the relationship between total tax revenue and the tax rate if G = tWN. (G=Government spending,...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT