STE Computer Programming - Q4 MODULE 7
STE Computer Programming - Q4 MODULE 7
Computer
Programming
Quarter IV – Module 7:
Key Concepts on
Sorting Algorithms
Republic Act 8293, section 176 states that: No copyright shall subsist in any work
of the Government of the Philippines. However, prior approval of the government agency or
office wherein the work is created shall be necessary for exploitation of such work for profit.
Such agency or office may, among other things, impose as a condition the payment of
royalties.
Borrowed materials (i.e., songs, stories, poems, pictures, photos, brand names,
trademarks, etc.) included in this module are owned by their respective copyright holders.
Every effort has been exerted to locate and seek permission to use these materials from
their respective copyright owners. The publisher and authors do not represent nor claim
ownership over them.
Each SLM is composed of different parts. Each part shall guide you step-by-
step as you discover and understand the lesson prepared for you.
At the end of each module, you need to answer the test to self-check your
learning. Answer keys are provided for each activity and test. We trust that you will
be honest in using these.
In addition to the material in the main text, Notes to the Teacher are also
provided to our facilitators and parents for strategies and reminders on how they
can best help you on your home-based learning.
Please use this module with care. Do not put unnecessary marks on any
part of this SLM. Use a separate sheet of paper in answering the exercises and
tests. And read the instructions carefully before performing each task.
If you have any questions in using this SLM or any difficulty in answering
the tasks in this module, do not hesitate to consult your teacher or facilitator.
Thank you.
ii
iii
Explore
In this module, you are expected to identify, evaluate and demonstrate the
different sorting algorithms:
a. Bubble Sort
b. Insertion Sort
c. Selection Sort
d. Merge Sort
1
Learn
Categories of Sorting
The techniques of sorting can be divided into two categories. These are:
Internal Sorting
External Sorting
Internal Sorting: If all the data that is to be sorted can be adjusted at a time in the
main memory, the internal sorting method is being performed.
2
hard disk, floppy disk, magnetic tapes etc, then external sorting methods are
performed.
Shuffle a deck of cards and get 5 cards. Arrange the cards in ascending order of
value. What makes it easy to arrange the cards?
Shuffle the deck of cards again. Arrange the entire deck of cards in ascending
order of value. What makes it difficult to arrange the cards?
When the number of elements ‘n’ is small, these considerations are irrelevant as
the power and capacity of computers have drastically improved. However, when
we are talking about billions of data to be sorted, sorting algorithm complexity
and efficiency become an issue.
Best case
Worst case
Average case
3
Best case scenario happens when the list is already sorted. Worst case is when
the list has been invertedly sorted. An efficient sorting algorithm must have a run
time consistent in all cases.
The result of these cases is often a formula giving the average time required for
a particular sort of size 'n.' Most of the sort methods have time requirements that
range from (n log n) to (n2), read as ‘Oh of n log of n’ and ‘Oh of n squared’.
An algorithm running at (n) means that the running time would linearly
increase as the number ‘n’ increases. On the other hand, if the algorithm is
running at (n2), then the running time exponentially increase as ‘n’ increases.
We could represent the running time f(n) where between these functions f(n) = n,
f(n) = n log n, and f(n) = n2, the last function would give a higher value of f(n) for any
value of n greater than 1. It means, that would require higher running time.
Directions: Arrange the jumbled letters to create words or terms related to sorting
techniques.
1. UBEBBL ROST
2. OIESRNTIN SROT
3. NESLETCIO ORTS
4. EMGRE TRSO
Bubble Sort
Insertion Sort
Selection Sort
Merge Sort
4
Bubble Sort Algorithm
Bubble Sort is a sorting algorithm where each element is treated as bubble.
Each bubble is compared to every other bubble and either the current bubble or
the bubble being compared to is brought up in the new sorted sequence. This is
repeated until all bubbles are compared to every other bubble. The resulting
sequence is sorted according to the comparison implemented, that is either sorted
in ascending or descending order.
Because Bubble Sort iterates every bubble and compares to every other
bubble during in each iteration, essentially Bubble Sort is running at (n2) or
running time exponentially increases as the number of elements to be sorted
increases.
There are different implementations of bubble sort. The main identifying
feature of the algorithm is its iteration (loop) inside another iteration (loop). Inside
the second loop is the evaluation or comparison of 2 elements and swapping if the
comparison condition is satisfied.
In implementation, to arrange N elements in ascending order, and for that,
you have to begin with 0th element and compare it with the first element. If the
0th element is found greater than the 1st element, then the swapping operation will
be performed, i.e., the two values will get interchanged. In this way, all the
elements of the array get compared.
5
Below given figure shows how Bubble Sort works:
6
Below is a simple code implementation of the pseudo-code and illustration
described above:
In your activity 1 above, one technique that you may have employed is to
start at one (1) card as sorted part, get the next card and insert it in the sorted
part. After that point, you got 2 cards sorted already. You then take the 3 rd card
and insert it in the sorted part. Your sorted part becomes 3 cards already. You take
another card and do the insertion again to the sorted part until all cards are in the
sorted part. These steps are best described as Insertion Sort scheme.
1. algorithm Insertion_sort(list)
2. Pre: list != fi
3. Post: list has been sorted into values of ascending order
4. unsorted <- 1
5. while unsorted < list.Count
7
6. hold <- list[unsorted]
7. i = unsorted - 1
8. while i >= 0 and hold < list[i]
9. list[i + 1] <- list[i]
10. i <- i - 1
11. end while
12. list[i + 1] <- hold
13. unsorted <- unsorted + 1
14. end while
15. return list
16. end Insertion_sort
8
The below-given figure shows how Selection Sort works:
1. algorithm Insertion_sort(list)
2. Pre: list != fi
3. Post: list has been sorted into values of ascending order
4. for i <- 0 to list:Count – 2
5. minIndex <- i + 1
6. for j <- i to list:Count - 1
7. if list[j] < list[minIndex]
8. minIndex <- j
9. end for
10. if list[i] < list[minIndex]
11. swap(list[i], list[minIndex])
12. end for
13. return list
14. end Insertion_sort
9
Example of selection sort in programming:
public static void selectionSort(int[] list) {
for (int i=0; i<list.length-1; i++) {
int minIndex = i+1;
for (int j=minIndex; j<list.length; j++) {
if (list[j] < list[minIndex]) {
minIndex = j;
}
}
if (list [i] > list[minIndex]) {
swapValue(list, i, minIndex);
}
}
}
10
Figure 3. Merge Sort Technique
Algorithm for Merge Sort
11
23.increment leftIndex
24.else
25.temp[tempIndex]=list[rightIndex]
26.increment tempIndex
27.increment rightIndex
28.end if
29.end while
30.if leftIndex <= mid //while left part has elements to merge
31.temp [tempIndex,mid] <-list[leftIndex,mid]
32.end if
33.if rightIndex <= end //while right part has elements to merge
34.temp [tempIndex,end] <-list[rightIndex,end]
35.end if
36.list [start, end] <- temp
37.end merge
public static void merge(int[] list, int start, int mid, int end) {
int temp[]= new int[end-start+1];
int leftIndex = start;
int rightIndex = mid+1;
int tempIndex = 0;
while (leftIndex <= mid && rightIndex <= end) {
if (list[leftIndex] <= list[rightIndex]) {
temp[tempIndex] = list[leftIndex];
tempIndex++;
leftIndex++;
} else {
temp[tempIndex] = list[rightIndex];
tempIndex++;
rightIndex++;
}
}
if (leftIndex <= mid) {
for (int i=leftIndex; i<=mid; i++) {
temp[tempIndex] = list[i];
tempIndex++;
12
}
}
if (rightIndex <= end) {
for (int i=rightIndex; i<=end; i++) {
temp[tempIndex] = list[i];
tempIndex++;
}
}
for (int i=0; i<temp.length; i++) {
list[start+i]=temp[i];
}
}
The table below shows a comparison of running times between the sorting
algorithm at best, average and worst cases.
Engage
Directions: Choose only the letter of your choice. Write your answers on a ¼
piece intermediate paper.
1. What are the correct intermediate steps of the following data set when it is
being sorted with the bubble sort as described above? 15,20,10,18
13
A. 15,10,20,18 -- 15,10,18,20 -- 10,15,18,20
A. 10 B. 2 C. 5 D. 25
4. What is the max. number of comparisons that can take place in a bubble sort
as implemented above? Assume there are n elements in the array.
5. What are the worst case and best-case time complexity of bubble sort,
respectively?
Apply
Directions: Sort this array in an increasing order using the Bubble Sort
Algorithm as described above. Write the correct answer with appropriate
solution. Write your answer in a whole piece of paper.
14
Problem1:
1 9 11 6 15 2
Problem 2:
2 7 4 1 5 3
Problem 3:
8 2 4 1 3
Problem 4:
15 20 10 18
Problem 5:
5 1 6 2 4 3
Assess
Directions: Solve the following and write your answer on 1 whole piece of paper.
(5 points for each item)
15
1. What are the correct intermediate steps of the following data set when it is
being sorted with the Bubble Sort? 5,6,1,9,7, 12? Write your solution.
2. What are the correct intermediate steps of the following data set when it is
being sorted with the Selection Sort? 2,8,5,3,9,4,1? Write your solution.
3. What are the correct intermediate steps of the following data set when it is
being sorted with the Merge Sort? 2,8,5,3,9,4,1,7? Write your solution.
4. What are the correct intermediate steps of the following data set when it is
being sorted with the Insertion Sort? 2,8,5,3,9,4? Write your solution.
Reflect
1. What is the most important thing you learn from this module?
3. Where did you encounter difficulties in this lesson or module, and what did you
do to deal with it?
16
17
Answer Key
Engage
1. B
2. D
3. A
4. B
5. A
Apply
Solution no. 1
10 9 11 6 15 2
9 10 11 6 15 2
9 10 6 11 15 2
9 10 6 11 2 15
Solution no. 2
2 7 4 1 5 3
2 4 7 1 5 3
2 4 1 7 5 3
2 4 1 5 3 7
Solution no. 3
8 2 4 1 3
2 8 4 1 3
2 4 8 1 3
2 4 1 8 3
2 4 1 3 8
Solution no. 4
8 2 4 1 3
2 8 4 1 3
2 4 8 1 3
2 4 1 8 3
2 4 1 3 8
Solution no. 5
15 20 10 18
15 10 20 18
15 10 18 20
10 15 18 20
18
Assess:
References
19
Meinecke, Lonny. "What Is An Algorithm In Programming? - Definition, Examples &
Analysis". Study.Com. Accessed 10 February 2021.
https://study.com/academy/lesson/what-is-an-algorithm-in-programming-
definition-examples-analysis.html.
20
For inquiries or feedback, please write or call:
21