Algorithms and Data Structures-Sorting Algorithms
Algorithms and Data Structures-Sorting Algorithms
Advanced Level
CC By Jacob Zvirikuzhe
Objective(s)
Explain how to sort elements using bubble sort and
quicksort algorithms.
Trace bubble sort and quicksort algorithms.
Sorting Algorithms
Sorting refers to arranging data in a particular format.
A sorting algorithm specifies the way to arrange data in a particular order.
Sorting algorithms are ways to organize an array of items from smallest to
largest.
Following are some of the examples of sorting in real-life scenarios −
• Telephone Directory − The telephone directory stores the telephone
numbers of people sorted by their names, so that the names can be
searched easily.
• Dictionary − The dictionary stores words in an alphabetical order so that
searching of any word becomes easy.
Bubble Sort Algorithm
• This sorting algorithm is comparison-based algorithm in which each
pair of adjacent elements is compared and the elements are swapped
if they are not in order.
Consider the following array
20 10 7 17 15
• The first two elements are compared. If the second element is smaller
than the first, the two are swapped.
20 10 7 17 19
Bubble Sort Algorithm
10 and 20 must be swapped.
10 20 7 17 19
But 10 and 7 are not in sorted positions, the two values are swapped
again.
7 10 20 17 19
Bubble Sort Algorithm
Next we compare 20 and 17. The two values are not in sorted positions
so they need to be swapped.
7 10 17 20 19
7 10 17 19 20
Bubble Sort Algorithm
Procedure BubbleSort(List)
Flag = False
FOR count = 1 TO N-1
If List[count] > List[Count + 1] THEN
Temp = List [Count]
List[Count]= List[Count + 1]
List[Count + 1] = Temp
Flag = True
END IF
END FOR
UNTIL Flag = False OR N-1
END PROCEDURE
Bubble Sort Algorithm
Activity 1
Describe how to sort the array below using bubble sort;
R = {100, 40, 35, 50, 30}
Using the trace table show how the array R, can be sorted using bubble
sort.
Quick Sort Algorithm
• Quick sort algorithm based on partitioning of array of data into
smaller arrays.
• The pivot value divides the list into two parts. And recursively, we find
the pivot for each sub-lists until all lists contains only one element.
Example: Sort the following array using Quick Sort.
20 10 7 17 15
Solution
On the left, each sublist contains one element therefore the sublist has
been sorted.
Quick Sort Algorithm
On the right hand side: