Docsity

Notes on Sorting Algorithms - Computer Science I | COP 3502, Study notes of Computer Science

Toggle sidebar
bg1
Tracing Examples
As promised, this set of notes begins with a slightly different way of tracing code.
These are the same examples as in the previous set of notes, but the tracing is
maintained in a slightly different fashion.
Example 1
In the algorithms below the numbers preceding each line are for reference
purposes only and are not part of the algorithm.
1 void main ( ) {
2 int numbers [10];
3 int i, k, total;
4 //read in the numbers
5 for (i=0; i<=9; i++)
6 {
7 printf(“Enter your number:\n” );
8 scanf(“%d”, &numbers[ i ]);
9 }
10 //sum the numbers
11 total = 0;
12 for (k=0; k <=9; k++)
13 {
14 total = total + numbers[ k ];
15 }
16 printf(“The sum of your numbers is: %d .\n“, total);
17 }
The trace
Suppose the input is: 2, 4, 6, 8, 10, 12, 14, 16, 18, 20
Statements 1 through 4 are either comments or defining variables
Statement 5 begins a loop which ends at line 9 – which does the following:
Graphically, when the loop on line 6 terminates, the “memory” looks like:
numbers array
index 0 1 2 3 4 5 6 7 8 9
value 2 4 6 8 10 12 14 16 18 20
Sorting Algorithms Continued - 1
Sorting Algorithms Continued
pf3
pf4
pf5
pf8
pf9
pfa

Partial preview of the text

Download Notes on Sorting Algorithms - Computer Science I | COP 3502 and more Study notes Computer Science in PDF only on Docsity!

Tracing Examples As promised, this set of notes begins with a slightly different way of tracing code. These are the same examples as in the previous set of notes, but the tracing is maintained in a slightly different fashion. Example 1 In the algorithms below the numbers preceding each line are for reference purposes only and are not part of the algorithm. 1 void main ( ) { 2 int numbers [10]; 3 int i, k, total; 4 //read in the numbers 5 for (i=0; i<=9; i++) 6 { 7 printf(“Enter your number:\n” ); 8 scanf(“%d”, &numbers[ i ]); 9 } 10 //sum the numbers 11 total = 0; 12 for (k=0; k <=9; k++) 13 { 14 total = total + numbers[ k ]; 15 } 16 printf(“The sum of your numbers is: %d .\n“, total); 17 } The trace Suppose the input is: 2, 4, 6, 8, 10, 12, 14, 16, 18, 20 Statements 1 through 4 are either comments or defining variables Statement 5 begins a loop which ends at line 9 – which does the following: Graphically, when the loop on line 6 terminates, the “memory” looks like: numbers array index 0 1 2 3 4 5 6 7 8 9 value 2 4 6 8 10 12 14 16 18 20

Sorting Algorithms Continued

total i k All of total, i, and k are undefined at this point in the algorithm Statement 10 is a comment Statement 11: assigns total the value of 0 Statement 12 begins a for-loop that ends at statement 15 Loop terminates. Statement 16 prints: The sum of your numbers is: 110. The final state of the memory looks like the following: Numbers array index 0 1 2 3 4 5 6 7 8 9 value 2 4 6 8 10 12 14 16 18 20 total i k i is undefined Example 2 Assume that we have an array named X which contains the values shown below. What are the values in every variable that appears in this algorithm after the loop has completed? Determine your answers by tracing the algorithm’s execution. Array X index 0 1 2 3 4 5 value 4 2 6 1 5 3 0 void main ( ) {

The mergesort sorting algorithm uses the divide and conquer strategy in which the original problem is split into two half-size, recursively solved problems. If the overhead of the base case was linear [O(N)] then the overall running time of the algorithm was O(N log 2 N). The mergesort is such an algorithm and is commonly employed for external sorting. The mergesort algorithm is a recursive, subquadratic algorithm as follows:

  1. if the number of items to sort is 0 or 1, return.
  2. recursively sort the first and second halves separately.
  3. merge the two sorted halves into a single sorted group. Since this algorithm uses the divide and conquer strategy and employs the halving principle, we know that the sorting is done in O(log 2 N) and thus we need only to show that merging two sorted groups into a single sorted group can be performed in linear time to prove the running time is O(N log 2 N). A linear merge algorithm A linear merge algorithm requires three separate arrays A, B, and C (two input and one output) plus an index counter per array (actr, bctr, and cctr). The index counters are initially set to the first position in each of their arrays with incrementation as follows: if A[actr] < B[bctr] C[cctr] = A[actr]; cctr++; actr++; } else { C[cctr] = B[bctr]; cctr++; bctr++; } Example: Linear Merge A B C

actr bctr cctr Example of a mergesort.

1 3 4 7 2 5 9 11^1 2

1 3 4 7 2 5 9 11^1 2 3

Quicksort With an average running time of O(N log 2 N), quicksort is the fastest-known sorting algorithm. Quicksort has a worst case running time of O(N 2 ) which can be made statistically impossible to achieve. Quicksort is a recursive algorithm whose performance is easy to prove yet has a tricky implementation since slight variations in the code can make significant differences in the running time. The quicksort algorithm is as follows:

  1. Call Quicksort(A).
  1. if the number of elements to be sorted is 0 or 1, return.
  2. pick any element v in the array A. (this is the pivot element)
  3. partition A- {v} into two disjoint groups: Left = {xA-{v}| x  v} and Right = {xA-{v}| x  v}.
  4. Return the result of Quicksort(Left), followed by v , followed by Quicksort(Right). Notes: base case includes possibility that the number of elements is 0 since the recursive calls may generate empty subsets. Any element can theoretically be the pivot element, although in reality the pivot element is not randomly chosen. The partitioning must be performed in place so that no additional arrays are required. Quicksort outperforms mergesort because the time required to partition the array is less than the time required to merge two arrays. Analysis Best Case: The partitions are always ½ the size of the input (at each recursive step) – thus by the halving principle the sorting component requires O(log 2 N) and with linear overhead for the base case – we have O(N log 2 N) which is equal to that of the mergesort. Worst Case: The partitions are very lopsided, meaning that either |L| = 0 or n- or |R| = n-1 or 0 at each recursive step. Suppose that T(N) is the time for Quicksort on array of N elements, Left contains no elements, Right contains all of the elements except the pivot element (this means that the pivot element is always chosen to be the smallest element in the partition), 1 time unit is required to sort 0 or 1 elements, and N time units are required to partition a set containing N elements. Then if N > 1 we have: T(N) = T(N-1) + N This means that the time required to quicksort N elements is equal to the time required to recursively sort the N-1 elements in the Right subset plus the time required to partition the N elements. By telescoping the equation above we have: T(N) = T(N-1) + N T(N-1) = T(N-2) + (N-1) T(N-2) = T(N-3) + (N-2) …
  • T(2) = T(1) + 2

Consider the problem of sorting the sequence S = {a, b, c} composed of three distinct items; that is: a  b and a  c and b  c. The figure below illustrates a possible sorting algorithm in the form of a binary decision tree. Each node of the decision tree represents one binary comparison (in each node of the tree exactly two elements are compared). Since there are two possible outcomes for each comparison, each non-leaf node in the tree will be of degree two. Suppose that a < b < c in our example. Consider how the algorithm determines this fact. Y N Y N Y N Y N Y N A Decision Tree for Comparison Sorting For the example, the first comparison compares a and b which will reveal that a < b (since we assumed a < b < c). The second comparison compares a and c which will determine that a < c. At this point it has been determined that a < b and a < c , yet the relative order of b and c has not yet been determined. Therefore, a third comparison is required to determine the relative order of b and c. Notice that the “algorithm” works correctly in all cases because every permutation of the sequence S appears as a leaf node in the decision tree. Furthermore, the number of comparisons required in the worst case is equal to the height of the decision tree! Any sorting algorithm that uses binary (element) comparisons can be represented by a binary decision tree. The height of that decision tree will determine the worst case running time of the algorithm. In general, the size and a < b a < c a < c b < c b < c c < a < b b < a < c a < b < c a < c < b b < c < a c < b < a

shape of the decision tree depends on the particular sorting algorithm and the number of elements to be sorted. Given an input sequence of n items to be sorted, every binary decision tree that correctly sorts the input sequence must have at least n! leaves (one for each permutation of the input). Therefore, since the maximum number of leaf nodes in a binary tree of height h is 2 h , that the height of the binary decision tree is at least  log 2 n!. Therefore,

        n i 1 n/ 2 i 1 log 2 n! log 2 n! log 2 i log 2 n/ 2 n/ 2 log 2 n/ 2 (nlogn) Since the height of the decision tree is (n log n), the number of comparisons done by any sorting algorithm that sorts using only binary comparisons is (n log n). Assuming that each comparison can be done in constant time, the running time of any such algorithm is (n log n).