SCE Assessment - SCE Support Center

Download Report

Transcript SCE Assessment - SCE Support Center

CSCI 3333 Data Structures
Sorting Exercises
by
Dr. Bun Yue
Professor of Computer Science
[email protected]
http://sce.uhcl.edu/yue/
2013
General Sorting Algorithm

Linda claims to have an sorting
algorithm to sort an array S into a
sorted array T.
1.
2.
3.
4.
Give an O(n) algorithm isSorted to check
whether T is sorted.
Explain why isSorted is not sufficient to prove
that a particular output T is a sorting of S.
Describe what additional information Linda’s
algorithm could output so that her
algorithm’s correctness could be established
on any given S and T in O(n) time.
With the additional information from (3),
construct an O(n) algorithm to check whether
T is a sorting of S.
Shell Sort

Shown the evolution of Shell Sort
using a gap sequence of (5,3,1)
with the array {29, 11, 18, 50, 20,
33, 13, 80, 79, 61, 11, 54, 77, 68,
22, 60, 56}. Show each recursive
call and the action involved.
QuickSort

Use the C++ implementation in the lecture:
template <typename ElementType>
void Split(ElementType x[],int first, int last, int& pos)
(
ElementType pivot = x[left]; // pivot element
int left = first, // index for left search
right = last; // index for right search
while (left < right)
{
// Search from right for element <= pivot
while (x[right] > pivot)
right--;
// Search from left for element > pivot
while (left < right && x[left] <= pivot)
left++;
// Interchange elements if searches haven’t met
if (left < right)
Swap(x[left], x[right]);
}
// End of searches; place pivot in correct position
pos = right;
x[first] = x[pos];
x[pos] = pivot;
}
QuickSort
template <typename ElementType>
void Quicksort(ElementType x[], int first, int last)
{
int pos; // final position of pivot
if (first < last) // list has more than one element
{
// Split into two sublists
Split(x, first, last, pos);
// Sort left sublist
Quicksort(x, first, pos - 1);
// Sort right sublist
Quicksort(x, pos + 1, last);
}
// else list has 0 or 1 element and
// requires no sorting
return;
}
This function is called with a statement of the form
Quicksort(x, 1, n);
QuickSort

Show the evolution of sorting the
array [10, 7, 3, 22, 90, 33, 21, 4,
90, 68, 50] by showing each
recursive calls and their actions.
Questions and Comments?