This action might not be possible to undo. Are you sure you want to continue?
Differences in the Function quicksort in Programs qsort.c and quicksort2.c
qsort.c: The function, quicksort, is a recursive function. It makes two calls to itself at the very end of its subroutine. The reason that this program sometimes fails is due to the second call quicksort makes to itself. The 2nd call quicksort makes to itself will only return when the expression, (n-last-1), evaluates to less than or equal to one. The program never returns from that second call because last remains zero which doesn’t decrement n fast enough in the above expression. The variable n is the size of the array and is therefore very large when the array is very large. The variable last is incremented only when a number smaller than the pivot is found and sorted. Quicksort uses an algorithm that randomly picks a number from an array that is passed to it. When an array is very large but is filled with only a few different numbers, the probability that the function will randomly select a number that is less than or equal to most of the other numbers in the array is very high as opposed to an array that is full of many different kinds of numbers. The following example illustrates this concept: Suppose a 10,000 element array was filled only with the numbers 1 and 2. The probability that the lowest (or equal to) number, 1, will be selected as a pivot is much greater than the probability of the lowest (or equal to) number being selected if the array was filled with all numbers between 1 and 10,000. As stated above, quicksort depends upon the variable, last, to decrement n and bring the expression (n-last-1) to less than or equal to 1. The variable, n, only increments when a number less than the pivot is found and sorted. Therefore, when the pivot is less than or equal to all numbers in the array, n is zero and the amount of calls to quicksort becomes larger and larger until the stack can no longer contain all the information being put into it by a repeated amount of calls with no returns. This is why the program crashes. quicksort2.c: This quicksort implementation is recursive and uses three key variables: one variable has the highest array index which marks the last element in the given array, the second is a lower boundary for the given array which is constantly increasing for every element that is found to be lower than the pivot, and the last variable adjusts the prior two variables and sometimes acts as both an upper and lower boundary. This implementation of quicksort does not break down for large or small sets of numbers. It uses two base cases and a while loop that check the lower and upper bounds and return the function if they have met or overlapped.