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

from typing import List def longest_chain(submatrix: List[int]) -> int: """ Given a list of integers, return...
from typing import List def longest_chain(submatrix: List[int]) -> int: """ Given a list of integers, return the length of the longest chain of 1's that start from the beginning. You MUST use a while loop for this! We will check. >>> longest_chain([1, 1, 0]) 2 >>> longest_chain([0, 1, 1]) 0 >>> longest_chain([1, 0, 1]) 1 """ i = 0 a = [] while i < len(submatrix) and submatrix[i] != 0: a.append(submatrix[i]) i += 1 return sum(a) def largest_rectangle_at_position(matrix: List[List[int]], x:...
def largest_rectangle_in_matrix(matrix: List[List[int]]) -> int: """ Returns the area of the largest rectangle in <matrix>. The...
def largest_rectangle_in_matrix(matrix: List[List[int]]) -> int: """ Returns the area of the largest rectangle in <matrix>. The area of a rectangle is defined as the number of 1's that it contains. Again, you MUST make use of <largest_rectangle_at_position> here. If you managed to code largest_rectangle_at_position correctly, this function should be very easy to implement. Similarly, do not modify the input matrix. Precondition: <matrix> will only contain the integers 1 and 0. >>> case1 = [[1, 0, 1, 0, 0], ... [1,...
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...
Given the root C++ code: void sort() {    const int N = 10;    int...
Given the root C++ code: void sort() {    const int N = 10;    int x[N];    for(int i = 0; i < N; i++)    {        x[i] = 1 + gRandom-> Rndm() * 10;        cout<<x[i]<<" "; }    cout<<endl;    int t;       for(int i = 0; i < N; i++)    {    for(int j = i+1; j < N; j++)    {        if(x[j] < x[i])        {   ...
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++
import random #the menu function def menu(list, question): for entry in list: print(1 + list.index(entry),end="") print(")...
import random #the menu function def menu(list, question): for entry in list: print(1 + list.index(entry),end="") print(") " + entry) return int(input(question)) plz explain this code
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...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT