4-Sorting algorithms (selection - insertion - bubble - Quick ) Flashcards
Goal of sorting ?
The goal of sorting is to rearrange the elements of S ( a sequence {s1,s2,s3,…,sn} of n>=0 elements drawn from a universe U ) and produce another sequence S’ such that elements of S appear in order
What does it mean to say “in order”?
Given a relation, eg. < :
- It has to be a total order (simple order)
- For all pairs of elements (i,j), exact one of the following is true: i i
What is a stable sort?
When it preserves the relative order of the items with duplicated keys on the list
Advantages of a stable sort:
- more efficient in practice
- in general, easier to be parallelised
- allow multi-key sort to be easily implemented by combining multiple runs the sorting algorithm.
How does selection sort work ?
selection sort orders a list of elements by finding the
index of the maximum element (selecting the element) and putting it in its place in the list
Characteristics of selection sort ?
- It is a simple algorithm
- it is inefficient for large values of n, where n is the size of the list.
- Can be easily implemented on linked lists
Write down the Selection sort algorithm.
void selectionSort(int list[]) { \_\_\_\_int last = list.length; \_\_\_\_int maxPos; \_\_\_\_while (last > 0) { \_\_\_\_\_\_\_\_maxPos = findMax(list,last+1); \_\_\_\_\_\_\_\_swap(list,maxPos,last); \_\_\_\_\_\_\_\_last--; \_\_\_\_} }
WORST CASE selection sort
theta(n^2)
Explain Insertion Sort :
The idea here is that we get an element and insert it in the position it belongs.
Used frequently when we want to generate another list with the elements
sorted
It can be also done in place, that is, without requiring an extra list
After each outer loop interaction one element in the list has been placed in his final location
What performance do elementary algorithms have ?
Theta(n^2)
Examples of elementary algorithms:
Insertion and selection sort
Write an insertion sort algorithm :
void insertionSort(int list[]) { \_\_\_\_int pos = list.length-1; \_\_\_\_while (pos > 0) { \_\_\_\_\_\_\_\_ indexNew = pos – 1; \_\_\_\_\_\_\_\_valueNew = list[indexNew]; \_\_\_\_\_\_\_\_\_while ((indexNew < list.length-1) && \_\_\_\_\_\_\_\_\_\_\_\_(valueNew > list[indexNew+1])) { \_\_\_\_\_\_\_\_\_\_\_\_list[indexNew] = list[indexNew+1]; \_\_\_\_\_\_\_\_\_\_\_\_ indexNew++; \_\_\_\_\_\_\_\_} \_\_\_\_list[indexNew] = valueNew; \_\_\_\_ pos--; }
Is insertion sort stable ?
dunno google it
Is selection sort stable ?
dunno google it
Bubble Sort:
Bubble sort is one of the simplest algorithms for sorting a list but also one of the slowest.
Theoretically speaking it has the same efficiency of selection sort