Question

In: Computer Science

Write a program in python that implements quicksort, first using recursion and then without recursion.

Write a program in python that implements quicksort, first using recursion and then without recursion.

Solutions

Expert Solution

Using Recursion:

def make_partition(arr, low, high):
        i = (low-1)              # index of smaller element
        temp = arr[high]

        for j in range(low, high):
                # If current element is smaller than or equal to temp then swap
    #element and increment i by 1
                if arr[j] <= temp:
                        i = i+1
                        arr[i], arr[j] = arr[j], arr[i] #swap element

        arr[i+1], arr[high] = arr[high], arr[i+1]
        return (i+1)

def quickSort(arr, low, high):
  #check if array has only one element the return array
        if len(arr) == 1:
                return arr
        if low < high:
                #fnd partitioning_index by calling function make_partition()
                partitioning_index = make_partition(arr, low, high)

                #sort elements before partition and after partition
                quickSort(arr, low, partitioning_index-1)
                quickSort(arr, partitioning_index+1, high)

#empty array to be sorted
arr = []

#get number of element from user
size = int(input("Enter how many element you want to sort : "))

#get one by one element from user 
for i in range(1,size+1):
  element = int(input("Enter element of "+str(i)+" : "))
  arr.append(element)

#call function to sort array
quickSort(arr, 0, size-1)

#print sorted array
print(("-"*20)+" Sorted Array "+("-"*20))

for i in range(size):
        print("%d" % arr[i])

Output:

Without Recursion:

def partition(arr,l,h): 
    i = ( l - 1 ) 
    x = arr[h] 
  
    for j in range(l , h):
        # If current element is smaller than or equal to temp then swap
        #element and increment i by 1 
        if   arr[j] <= x: 
            i = i+1
            arr[i],arr[j] = arr[j],arr[i] 
  
    arr[i+1],arr[h] = arr[h],arr[i+1] 
    return (i+1) 

def quickSort(arr,l,h): 
  
    # Create stack 
    size = h - l + 1
    stack = [0] * (size) 
  
    # initialize top of stack 
    top = -1
  
    # push values of l and h to stack 
    top = top + 1
    stack[top] = l 
    top = top + 1
    stack[top] = h 
  
    # Keep popping from stack while is not empty 
    while top >= 0: 
  
        # Pop h and l 
        h = stack[top] 
        top = top - 1
        l = stack[top] 
        top = top - 1
  
        # Set middle element at its correct position in 
        # sorted array 
        middle = partition( arr, l, h ) 
  
        # If there are elements on left side of middle, 
        # then push left side to stack 
        if middle-1 > l: 
            top = top + 1
            stack[top] = l 
            top = top + 1
            stack[top] = middle - 1
  
        # If there are elements on right side of middle, 
        # then push right side to stack 
        if middle+1 < h: 
            top = top + 1
            stack[top] = middle + 1
            top = top + 1
            stack[top] = h 
  


#empty array to be sorted
arr = []

#get number of element from user
size = int(input("Enter how many element you want to sort : "))

#get one by one element from user 
for i in range(1,size+1):
  element = int(input("Enter element of "+str(i)+" : "))
  arr.append(element)

#call function to sort array
quickSort(arr, 0, size-1)

#print sorted array
print(("-"*20)+" Sorted Array "+("-"*20))

for i in range(size):
        print("%d" % arr[i])

Output:


Related Solutions

Write a program that performs a merge-sort algorithm without using a recursion. Only using pointers. C++...
Write a program that performs a merge-sort algorithm without using a recursion. Only using pointers. C++ programming language; #include<iostream>
Create a program called DualPivotQuickSort.java that implements the QuickSort algorithm using Yaroslavskiy’s algorithm. The program should...
Create a program called DualPivotQuickSort.java that implements the QuickSort algorithm using Yaroslavskiy’s algorithm. The program should be able to do the following: accepts one command line parameter. The parameter specifies the path to a text file containing the integers to be sorted. The structure of the file is as follows: There will be multiple lines in the file (number of lines unknown). Each line will contain multiple integers, separated by a single whitespace. reads the integers from the text file...
Write a python program that implements a Brute Force attack on Shift Cipher. In this program...
Write a python program that implements a Brute Force attack on Shift Cipher. In this program there is only one input - ciphertext - is a sequence of UPPER CASE letters. To make it easy, the program will be interactive and will output all possible plaintexts and ask user which plaintext makes sense. As soon as user will decide YES, the program will stop searching and print the desired plaintext and the found SHIFT KEY.
Write a program that performs a merge-sort algorithm without using a recursion. c++ programming language(Only #inlclude...
Write a program that performs a merge-sort algorithm without using a recursion. c++ programming language(Only #inlclude <iostream>)
Write a python program. The function protocol implements the functionality of the diagnostic protocol. The main...
Write a python program. The function protocol implements the functionality of the diagnostic protocol. The main idea of this function is to call the functions that you have already implemented in the previous questions. See below for an explanation of exactly what is expected. def protocol(my_symptoms: Tuple[Set], all_patients_symptoms: Dict[str, Tuple[Set]], all_patients_diagnostics: Dict[int, str]) -> str: '''Return the diagnostic for my_symptoms based on the dictionary of patients symptoms (all_patients_symptoms) and the dictionary of patients diagnostics (all_patients_diagnostics). Hint: This function selects the...
PYTHON Find anagrams of a word using recursion. This a possible run of your program: Enter...
PYTHON Find anagrams of a word using recursion. This a possible run of your program: Enter a word or empty string to finish: poster The word poster has the following 6 anagrams: presto repost respot stoper topers tropes
Using python: Given a string x, write a program to check if its first character is...
Using python: Given a string x, write a program to check if its first character is the same as its last character. If yes, the code should output "True"
For these of string functions, write the code for it in C++ or Python (without using...
For these of string functions, write the code for it in C++ or Python (without using any of thatlanguage's built-in functions) You may assume there is a function to convert Small string into the language string type and a function to convert your language's string type back to Small string type. 1. int [] searchA,ll(string in...str, string sub): returns an array of positions of sub in in...str or an one element array with -1 if sub doesn't exist in in...str
need to write program on python, without using any other libraries like panda, numpy, etc. here...
need to write program on python, without using any other libraries like panda, numpy, etc. here is google link on csv file https://drive.google.com/file/d/1O3cC9JAPVkXSrddTR6RocpSV8NMHrmRx/view?usp=sharing There is a csv file, which is exel file, very big and what program should do: - Read a CSV file 'annual.csv' enterprise into a data structure - Count the number of rows and columns - Determine if the data contains empty values (should search in all rows) - Replace the empty values by 'NA' for strings,...
Write a Python 3 program called “parse.py” using the template for a Python program that we...
Write a Python 3 program called “parse.py” using the template for a Python program that we covered in this module. Note: Use this mod7.txt input file. Name your output file “output.txt”. Build your program using a main function and at least one other function. Give your input and output file names as command line arguments. Your program will read the input file, and will output the following information to the output file as well as printing it to the screen:...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT