You are on page 1of 25

10

Computer
Programming
Quarter IV – Module 7:
Key Concepts on
Sorting Algorithms

"Designed by macrovector / Freepik"


Computer Programming– Grade 10
Self-Learning Module
First Edition, 2020

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.

Published by the Department of Education – Regional Office VIII


Regional Director: Ma. Gemma M. Ledesma, CESO V
Assistant Regional Director: Arnulfo M. Balane, CESO V

Development Team of the Module


Writers: Imelda P. Arcillas and Erdenan S. Labrador
Language Editor/s: Raymund M. Pepito
Content Editor: Jessie M. Caber
Layout Artist: Junrell R. Lora; Erdenan S. Labrador
Management Team:
Rosemarie M. Guino EdD,OIC – Chief, CLMD
Ryan R. Tiu, EdD, EPS, CLMD – Science
Joy B. Bihag, EPS, CLMD – LRMS
Alejandro S. Almendras, Chief, CID
Juliet B. Montebon, EPS, CID – Science
Pia B. Chu, EPS, CID - LRMS

Printed in the Philippines by ________________________

Department of Education –Regional Office VIII

Office Address: Government Center, Candahug, Palo, Leyte


Telefax: 053 - 3233156
E-mail Address: region8@deped.go
Introductory Message
This Self-Learning Module (SLM) is prepared so that you, our dear learners,
can continue your studies and learn while at home. Activities, questions,
directions, exercises, and discussions are carefully stated for you to understand
each lesson.

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

Sorting refers to the operation or technique of arranging sets of data or a


collection of records called list, in some specific order.
Sorts are most commonly in numerical or a form of alphabetical (called
lexicographical) order, and can be in ascending (A-Z, 0-9) or descending (Z-A, 9-0)
order. A sorted array is an array that is in a particular order. For example, [a,b,c,d]
[a,b,c,d] is sorted alphabetically, [1,2,3,4,5][1,2,3,4,5] is a list of integers sorted in
increasing order, and [5,4,3,2,1][5,4,3,2,1] is a list of integers sorted in decreasing
order.
A Sorting Algorithm is a set of steps used to arrange a given array or list
elements according to a comparison operator on the elements. The comparison
operator is used to decide the new order of element in the respective data structure.
The comparison operator could just be a simple numerical comparator (greater
than /less than), lexicographic comparator (alphabetical ordering) or other more
complicated comparator giving weight for each list element and deciding which
comes first. The sorting algorithm is done when all the elements are already sorted.

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

A Review on Programming Algorithm

You can think of a programming algorithm as a recipe that describes the


exact steps needed for the computer to solve a problem or reach a goal. We've all
seen food recipes - they list the ingredients needed and a set of steps for how to
make the described meal. Well, an algorithm is just like that. In computer lingo,
the word for a recipe is a procedure, and the ingredients are called inputs. Your
computer looks at your procedure, follows it to the letter, and you get to see the
results, which are called outputs.

A programming algorithm describes how to do something, and your


computer will do it exactly that way every time. Well, it will once you convert your
algorithm into a language it understands! Your sorting algorithm is an example of a
programming algorithm taking a list of data or elements as an input, producing a
sorted equivalent list as an output.

Go back to your previous lessons to understand more on algorithms and


programming algorithms.

Sorting Algorithm as Computer Algorithm


Sorting algorithm is one of the early discussion points in Computer Science
as this is one of the basic internal operations of a computer system.

As discussed, sorting operation is important as that enable easy


identification of location of a data, record, or element. Sorting can also be used in
priority queues like when there are multiple computer tasks being ran by a
computer and it needs to decide which task to run first.

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.

External Sorting: When the data that is to be sorted cannot be accommodated in


the memory at the same time and some has to be kept in auxiliary memory such as

2
hard disk, floppy disk, magnetic tapes etc, then external sorting methods are
performed.

ACTIVITY 1: DECK OF CARDS

Directions: Do the activity as stated below and answer the corresponding


questions.

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?

The Complexity of Sorting Algorithms


The complexity of sorting algorithm calculates the running time of a function in
which 'n' number of items are to be sorted. The choice for which sorting method is
suitable for a problem depends on several dependency configurations for different
problems. The most noteworthy of these considerations are:

 The length of time spent by the programmer in programming a specific


sorting program
 Amount of machine time necessary for running the program

 The amount of memory necessary for running the program

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.

The Efficiency of Sorting Techniques


To get the amount of time required to sort an array of 'n' elements by a
particular method, the normal approach is to analyze the method to find the
number of comparisons (exchanges or swaps) required by it. Most of the sorting
techniques are data sensitive, and so the metrics for them depends on the order in
which they appear in an input array.
Various sorting techniques are analyzed in various cases and named these
cases as follows:

 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.

ACTIVITY 2: JUMBLE JUGGLE

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

Types of Sorting Techniques

 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.

Algorithm for Bubble Sort

1. algorithm Bubble_Sort (list)


2. Pre: list != fi
3. Post: list is sorted in ascending order for all values
4. for i <- 0 to list:Count – 1 //loop, meaning everything
from //lines 5-10 will be executed
when //i=0, i=1, i=2, … until
Count-1
5. for j <- i to list:Count – 1 //loop inside a loop (second
loop) // starting from i until Count-
1
6. if list[i] > list[j] //comparison
7. Swap(list[i]; list[j]) //swapping when condition is met
8. end if
9. end for
10. end for
11. return list
12. end Bubble_Sort

5
Below given figure shows how Bubble Sort works:

Figure 1. Example of how bubble sorting works.

6
Below is a simple code implementation of the pseudo-code and illustration
described above:

public static void bubbleSort(int[] list) {


for (int i = 0; i < list.length; i++) {
for (int j = i; j < list.length; j++) {
if (list[i] > list[j]) {
swapValue(list, i, j);
}
}
}
}

public static void swapValue(int[] list, int indexA, int indexB) {


int temp = list[indexA];
list[indexA] = list[indexB];
list[indexB] = temp;

Insertion Sort Algorithm

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.

Insertion sort is to some extent an interesting algorithm with an expensive


runtime characteristic having (n2) because the first element in the unsorted part
would be evaluated and inserted against the sorted list to determine its rightful
position.

Algorithm for Insertion Sort

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

Example of Insertion Sort in Programming:

public static void insertionSort(int[] list) {


int unsorted = 1;
while (unsorted < list.length) {
int hold = list[unsorted];
int i = unsorted - 1;
while (i >= 0 && hold < list[i]) {
list[i+1] = list[i];
i = i - 1;
}
list[i + 1] = hold;
unsorted = unsorted + 1;
}
}

Selection Sort Algorithm


The selection sort is a straightforward process of sorting values. In this
method, to sort the data in ascending order, the 0th element is compared with all
other elements. If the 0th element is found to be greater than the compared
element, the two values get interchanged. In this way after the first iteration, the
smallest element is placed at 0th position. The technique is repeated in the next
element and to its right side until the full array gets sorted.

8
The below-given figure shows how Selection Sort works:

Figure 2. Selection Sort Technique

Algorithm for Selection Sort

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);
}
}
}

Merge Sort Algorithm


Merge sort is another sorting technique and has an algorithm that has a
reasonably proficient space-time complexity - (n log n) and is quite trivial to apply.
This algorithm is based on splitting a list, into two comparable sized lists, i.e., left
and right and then sorting each list and then merging the two sorted lists back
together as one. This technique is also known as Divide and Conquer technique.
In essence, merge sort or any similar divide and conquer technique
implements recursion, a form of implementation where a process calls itself as a
subprocess.
Merge sort can be done in two types both having similar logic and way of
implementation. These are:

 Top down implementation


 Bottom up implementation
Below given figure shows how Merge Sort works:

10
Figure 3. Merge Sort Technique
Algorithm for Merge Sort

1. algorithm mergeSort(list, start, end)


2. Pre: list != fi
3. Post: list has been sorted into values of ascending order
4. if start >= end // end case, i.e, left and right partition already met
5. return list
6. end if
7. m <- (start + end) / 2
8. mergeSort(list, start, mid)
9. mergeSort(list, mid+1, end)
10.merge(list, left, mid, right)
11.end mergeSort
12.algorithm merge (list, start, mid, end)
13.Pre: list != fi
14.Post: list has been sorted into values of ascending order
15.temp new array with size end-start+1
16.leftIndex <- start
17.rightIndex <- mid + 1
18.tempIndex <- 0
19.while (leftIndex <= mid && rightIndex <= end) //while both left part and
right // part has elements to
merge
20.if list[leftIndex] <= list[rightIndex]
21.temp[tempIndex]=list[leftIndex]
22.increment tempIndex

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

Example of merge sort in programming:


public static void mergeSort(int[] list, int start, int end) {
if (start >= end) return;
int mid = (start + end) / 2;
mergeSort(list, start, mid);
mergeSort(list, mid+1, end);
merge(list, start, mid, end);
}

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];
}
}

Sorting Algorithm Comparison

The table below shows a comparison of running times between the sorting
algorithm at best, average and worst cases.

Table 1. Sorting Algorithm Comparison

Best Case Worst Case Average Case


Bubble Sort (n2) (n2) (n2)
Insertion Sort (n2) (n2) (n2)
Selection Sort (n2) (n2) (n2)
Merge Sort (n log n) (n log n) (n log n)

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

B. 10, 20,15,18 -- 10,15,20,18 -- 10,15,18,20

C. 15,20,10,18 -- 15,10,20,18 -- 10,15,20,18 -- 10,15,18,20

D. 15,18,10,20 -- 10,18,15,20 -- 10,15,18,20 -- 10,15,18,20

2. In a bubble sort structure, there is/are?

A. A single for loop B. Three for loops, all separate

C. A while loop D. Two for loops, one nested in the other

3. What is the minimum number of comparisons needed if there are 5 elements


in array x?

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.

A. (1/2)(n-1) B. (1/2)n(n-1) C. (1/4)n(n-1) D. None of the above

5. What are the worst case and best-case time complexity of bubble sort,
respectively?

A. (n2), (n2) B. (n2), (n3) C. (n), (n3) D. None of the above

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

Directions: Reflect on the following questions. Answer each heartily and


mindfully.

1. What is the most important thing you learn from this module?

2. What topic do you want to learn more about arrays?

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:

1. Bubble Sort Solution


5 6 1 9 7 12
5 6 1 9 7 12
5 1 6 9 7 12
5 1 9 6 7 12
1 5 9 6 7 12
1 5 6 9 7 12
1 5 6 7 9 12

2 Selection Sort Solution


2 8 5 3 9 4 1
1 8 5 3 9 4 2
1 2 5 3 9 4 8
1 2 3 5 9 4 8
1 2 3 4 9 5 8
1 2 3 4 5 9 8
1 2 3 4 5 8 9

3. Merge Sort Solution


2 8 5 3 9 4 1 7
2 8 5 3 9 4 1 7
2 8 3 5 9 4 1 7
2 8 3 5 4 9 1 7
2 3 5 8 1 4 7 9
1 2 3 4 5 7 8 9

4. Insertion Sort Solution


2 8 5 3 9 4
2 5 8 3 9 4
2 3 5 8 9 4
2 3 5 8 9 4
2 3 4 5 8 9

LEARN- ACTIVITY 2: JUMBLE LEARN- ACTIVITY 1: DECK OF


JUGGLE CARDS

1. Bubble Sort 1. Because of the few


number of cards, sorting is
2. Insertion Sort easy.
2. As the number of cards
3. Selection Sort increases, it becomes
difficult to arrange them.
4. Merge Sort

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.

"Merge Sort Quiz - Proprofs Quiz". Proprofs.Com. Accessed 10 February 2021.


https://www.proprofs.com/quiz-school/story.php?title=merge-sort-quiz.

"Sorting Techniques In Data Structures". W3schools.In. Accessed 10 February


2021. https://www.w3schools.in/data-structures-tutorial/sorting-techniques/.

20
For inquiries or feedback, please write or call:

Department of Education – Regional Office VIII – Curriculum and Learning


Management Division (CLMD) - Learning Resources Management Section (LRMS)

Government Center, Candahug, Palo, Leyte, 6501

Telefax: (053) 323-3156; 323-3854; 824-4627

Email Address: *region8@deped.gov.ph


*clmd.region8@deped.gov.ph *lrmds.region8@deped.gov.ph

21

You might also like