Lecture 04 - Sorting Algorithms
Lecture 04 - Sorting Algorithms
By
Ritwik M
Based on the reference materials by Prof. Goodrich, OCW METU and Dr. Vidhya Balasubramanian
All images from Goodrich, Michael T., Roberto Tamassia, and Michael H. Goldw asser. Data structures and algorithms in Python. John Wiley & Sons, 2013.
• Complexity Analysis
– Counting Method
• Primitive operations are identified and counted to
analyze cost
– Asymptotic Analysis
• Big Oh
• Verification of Big Oh
• Examples
• Exercises
Algorithm
To sort an array of size n in ascending order:
1: Iterate from arr[1] to arr[n] over the array.
2: Compare the current element (key) to its predecessor.
3: If the key element is smaller than its predecessor, compare it to
the elements before. Move the greater elements one position up
to make space for the swapped element.
• Source: Goodrich
Pseudocode
BubbleSort(inputList)
for all elements of list
if list[i] > list[i+1]
swap(list[i], list[i+1])
end if
end for
return list
14 27 33 10 35
14 27 10 33 35
10 14 27 33 35
8 Amrita Vishwa Vidhyapeetham Ritwik M
Amrita School of Engineering
Cost Analysis of Bubble Sort
Algorithm
To sort an array of size n in ascending order:
1: Set MIN to location 0
2: Search the minimum element in the list
3: Swap with value at location MIN
4: Increment MIN to point to next element
5: Repeat until list is sorted
20 33 27 10 35 19 42 44
• Find smallest
• Swap with current 10 33 27 20 35 19 42 44
• Mark current&Move 10 33 27 20 35 19 42 44
10 19 27 20 35 33 42 44
10 19 27 20 35 33 42 44
….
• Sorted Array 10 19 20 27 33 35 42 44
Source: Goodrich
Source: Goodrich
Source: Goodrich
Source: Goodrich
• and so on
• E, storing the elements in S equal to x(usually only the pivot if all elements are distinct)
• Sorting Algorithms
– Bubble
– Selection
– Insertion
– Merge
– Quick
• Time Complexity of the sorting Algorithms
• Examples
• Exercises