Implement a recursive quicksort algorithm

Assignment Help C/C++ Programming
Reference no: EM132107908

Programming C Assignment

 

Quicksort

Objectives

Learn to sort the values of an array

Practice using recursion

Practice implementing pseudocode

More practice with 1D arrays

Overview

For this lab, you will first populate an array with integer values provided by a user and then you will sort the array. You will implement a recursive quicksort algorithm.

Quicksort Algorithm

Quicksort, also known as the partition-exchange sort, is an efficient algorithm. From Wikipedia:

Quicksort first divides a large array into two smaller sub-arrays: the low elements and the high elements. Quicksort can then recursively sort the sub-arrays.

Pick an element, called a pivot, from the array.

Reorder the array so that all elements with values less than the pivor come before the pivot, while all elements with values greater than the pivot come after it (equal values can go either way). After this partitioning, the pivor is in its final position. This is called the partition operation.

Recursively apply the above steps to the sub-array of elements with smaller values and separately to the sub-array of elements with greater values.

The base case of the recursion is arrays of size zero or one, which never need to be sorted.

Implementation

At the top of your program, define a constant to restrict the maximum size of your array:

#define MAX_ARRAY_SIZE 50
You will implement 5 functions as well as your main function. The function prototypes are:

int populate_array( int array[] ); // Fill array with values from user. void print_array( int array[], int n ); // Print out the array values void swap( int array[], int index1, int index2 ); // Swap two array elements. void quicksort( int array[], int low, int high ); // Sorting algorithm int partition( int array[], int low, int high ); // Find the partition point (pivot)

These function prototypes will appear near the beginning of the program. Later in the program, you will provide the function implementation (you repeat the function prototype but this time you provide the function body as well).

main Function

In your main function, declare an array of size MAX_ARRAY_SIZE.

Next, call your function populate_array (described below) and save the result as variable n.

Print out the value in the array by calling your function print_array (described below).

Now call your sorting algorithm with the line:

quicksort(array, 0, n-1);
Now verify that your list is sorted by printing out the list. Once more, call the print_array function.

return 0; to exit with no errors to report.

populate_array Function

Prompt the user for an integer n:

Enter the value of n >
Validate that n is less than or equal to MAX_ARRAY_SIZE and greater than or equal to 0. f not, repeat Step 1.

Read in n integers from the user. You can assume these will be valid integers: either positive, negative or zero.

Scan in each integer one by one using a for loop. Save each value in the proper position in the array, beginning with index 0.

Return n.

print_array Function

Print the values in the array, one value per line, using a for loop.

TIP: Use the formatting code %+5d to print back each digit. This will slightly indent and display either a positive or negative sign in front of the number as appropriate.

swap Function

You will need to implement a "helper" swap function, which is called by the partition function. This function swaps the values located in index1 and index2 of array. There is nothing to return from this function.

TIP: Recall that an array name is a pointer to the first element Therefore, passing the array to your swap accmplishes pass-by-reference. You do not need to return anything because changes to the array will persist once the swap function returns.

quicksort function

Next, implement the quicksort function. Convert this pseudocode to valid C code.

Algorithm 1: Quicksort Algorithm procedure QUICKSORT( A, low, high ) if low < high then pivot <- partition( A, low, high ) quicksort( A, low, pivot - 1 ) quicksort( A, pivot + 1, high ) end if end procedure

TIP: The quicksort function does not have an explicit base case, but it does have one. When low == high, the array is of size 1 and nothing needs to happen. The function merely returns, thereby bottoming out the recursion.

partition Function

Lastly, implement the partition function. Convert this pseudocode to valid C code:

Algorithm 2: Partition procedure PARTITION( A, low, high ) pivot <- A[high] i <- low for j = low to high-1 do if A[j] <= pivot then swap(A, i, j) i <- i + 1 end if end for swap( A, i, high ) return i end procedure

Example Execution

Example 1

[esus] $ ./program2 Enter the value of n > -1 -1 is less than zero. Please try again. Enter the value of n > 100 100 exceeds the maximum array size. Please try again. Enter the value of n > 5 Enter 5 integers (positive, negative, or zero) > 7 0 -3 5 1 The initial array contains: +7 +0 -3 +5 +1 The array is now sorted: -3 +0 +1 +5 +7

Example 2

[esus] $ ./program2 Enter the value of n > 8 Enter 8 integers (positive, negative, or zero) > 4 -3 2 -1 0 -9 8 7 The initial array contains: +4 -3 +2 -1 +0 -9 +8 +7 The array is now sorted: -9 -3 -1 +0 +2 +4 +7 +8
Compile & Test

Compile your program using this gcc command. -std=c99 uses the C99 standard instead of the default C89 standard.

$ gcc -Wall -std=c99 program2.c -o program2

NOTE: Make sure you output is very similar to the example execution.

Reference no: EM132107908

Questions Cloud

Write a program that prints all numbers from 1 to n : Use the for statement in a program that prints all the numbers from n1 to n2, where n1 and n2 are two numbers specified by the user.
What is the current value of bank bills : If the current 180-day bill rate is 6.9% p.a., what is the current value of these bank bills to the nearest dollar?
Write a simulator in which one round of simulation involves : Write a simulator in which one round of simulation involves flipping a set of ten unfair coins in which there is a fixed likelihood.
Report the number of guesses made and terminate execution : Imagine that the user will write down a positive integer x on a piece of paper and your program will repeatedly ask questions in order to guess what x is.
Implement a recursive quicksort algorithm : For this lab, you will first populate an array with integer values provided by a user and then you will sort the array.
Track and manage the approval of teaching staff : ICT701 Relational Database Systems - ABC TechTraining need a database that will help us track and manage the approval of teaching staff
Define a function named bico : Define a function, named bico, that returns, from the ith expansion of the quantity (x + y), the jth coefficient.
Calculate the cost of your algorithm to prove : As a tie-breaking criterion, we adopt the total execution time of the algorithms used to solve the problems.
What is the internal rate of return : Today the bond's yield to maturity has risen to 8% (EAR). If I sell this bond now, what is the internal rate of return that I will earn on my investment?

Reviews

Write a Review

C/C++ Programming Questions & Answers

  Wap to calculate the area of the circle

Write a C++ program that prompts the user for the radius of a circle, then calls inline function circle Area to calculate the area of that circle.

  Student average and the class average

The program should accept student data until the word “DONE” is entered for the student name. This data should be printed to the screen in tabular format see below). The data also should be stored in a file. One student data should be stored per line..

  Write a c function to convert gallons-quarts-pints and cups

Write a C function named liquid() that is to accept an integer number and the addresses of the variables gallons, quarts, pints, and cups.

  Implement a version of the zombiedash

For this assignment you must implement a version of the 'ZombieDash' video game on the Teensy LCD board. The game is to be written in the C programming language. The implementation will make use of the LCD screen, buttons, LEDs, potentiometer, and..

  Program that uses an instance of the timeoff

Write a program that uses an instance of the TimeOff class you designed in Programming Challenge 5. The program should ask the user to enter the number of months an employee has worked for the company. It should then use the TimeOff object to calc..

  Show the dealer hole card until after the player stands

Do not show the dealer hole card until after the player stands, and do not show the dealer score until after the player stands. After the player stands, playout the dealer according to the rules = 17 stand.

  Write a function that collects integers from the user

Write a function that collects integers from the user until a 0 is encountered and returns them in a list in the order they were input (ML only).

  Describe the most fun aspect of the given assignment

Describe most fun aspect of the assignment. Describe the most challenging aspect of the assignment. Describe the most difficult aspect of the assignment to understand. Provide any suggestions for improving the assignment in the future.

  Which of the following correctly invokes the function f

which of the following correctly invokes the function F, assuming N is an integer variable?

  Prepare a program that frees invokes delete with a pointer

Prepare a program that frees invokes delete with a pointer to all the nodes on a given linked list.

  A linked list of your song structure in cd

The CD object should have a data member that is a linked list of your song structure that you have in CD.  The CD class needs a function that allows it to add a song to the object, that function would then append the song to that instance of the link..

  Function declare that it can throw an ioexception

Every C++ function that performs file I/O will thus need to either declare that it can throw an IOException, or contain a try-catch-finally block to deal with it. Response?

Free Assignment Quote

Assured A++ Grade

Get guaranteed satisfaction & time on delivery in every assignment order you paid with us! We ensure premium quality solution document along with free turntin report!

All rights reserved! Copyrights ©2019-2020 ExpertsMind IT Educational Pvt Ltd