Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Lecture 17
Sorting
z
z
slide 2
Lecture 17
SelectionSort
z
Basic idea:
for (i = start; i <= end - 1; i++)
select and put the i-th smallest element in A[i]
slide 3
Lecture 17
SelectionSort Example
//This class sorts an array, using the selection sort algorithm
public class SelectionSorter {
private int[] a; //reference to array to be sorted
//Constructs a selection sorter.
public SelectionSorter(int[] anArray) {
a = anArray;
}
//Sorts the array managed by this selection sorter.
public void sort( ) {
for (int i = 0; i < a.length - 1; i++) {
int minPos = minimumPosition(i);
swap(minPos, i);
}
}
slide 4
Lecture 17
slide 5
Lecture 17
Lecture 17
slide 6
Lecture 17
slide 7
Lecture 17
QuickSort
Basic idea:
1) Choose an element as a pivot.
2) Partition the input array into two subarrays so that
elements of first subarray <= pivot <= elements of second subarray
3) QuickSort the first subarray and QuickSort the second subarray.
z
slide 8
Lecture 17
QuickSort Example
public class QuickSorter {
private int[] a;
public QuickSorter(int[] anArray) {
a = anArray;
}
public void sort( ) {
sort(0, a.length - 1);
}
public void sort(int from, int to)
{
if (from >= to) return;
int p = partition(from, to);
sort(from, p);
sort(p + 1, to);
}
slide 9
Lecture 17
slide 10
slide 11
Lecture 17
Lecture 17
slide 12
slide 13
Lecture 17
>x
i
?
j
x
r
Lecture 17
slide 14
Lecture 17
slide 15
slide 16
Lecture 17