Week 4 - Sorting Algorithms I
Week 4 - Sorting Algorithms I
1. Introduction to Sorting
Sorting is rearranged a sequence of elements into numerical order based on the sort key(s).
2 Types:
Efficiency: A measure of the relative efficiency (time complexity) of a sort. Usually based on
number of comparisons and moves during sorting.
2. Selection Sort
Choose the largest or smallest number, swap it to beginning or ending and reduce the range by
one and restart until range = 1.
BigOh: O(n^2), Stability: No
3. Insertion sort
Sort a set of elements by inserting unsorted elements into existing sorted list.
1. Consider the 1st element as
sorted range
2. Compare the next element
and Insert it in the correct
order of the sorted range.
3. Increase the sorted range
and repeat step 2.
BigOh is O(n^2).Stability: Yes
4. Bubble sort
Bubble Sort is similar to bubbles in water, the bigger ones will raise faster to the surface
Algorithm:
1. Scan the array from left to right, exchange pairs of elements that are out-of- order.
2. Repeat the above process for (N-1) time where N is the number of elements in the array.
BigOh is O(n^2), Stability: Yes
5. Merge sort(Very nice):
• Divide: If S has at leas two elements (nothing needs to be done if S has zero or one elements),
remove all the elements from S and put them into two sequences, S1 and S2, each containing
about half of the elements of S. (i.e. S1 contains the first elements and S2 contains the remaining
elements.
• Recursion: Recursive sort sequences S1 and S2.
• Conquer: Put back the elements into S by merging the sorted sequences S1 and S2 into a
unique sorted sequence.
https://www.youtube.com/watch?v=4VqmGXwpLqc&t=1s
BigOh: O(nLogn), Stability: Yes