STE - Computer Programming - Q4 MODULE 7
STE - Computer Programming - Q4 MODULE 7
Computer
Programming
Quarter IV – Module 7:
Key concepts of 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
For the learner:
This module was designed to provide you with fun and meaningful opportunities
for guided and independent learning at your own pace and time. You will be
enabled to process the contents of the learning resource while being an active
learner.
iii
Learners can share their thoughts and feeling
about the lessons.
1. Use the module with care. Do not put unnecessary mark/s on any part of
the module. Use a separate sheet of paper in answering the exercises.
2. Read the instruction carefully before doing each task.
3. Observe honesty and integrity in doing the tasks and checking your
answers.
4. Finish the task at hand before proceeding to the next.
5. Return this module to your teacher/facilitator once you are through with it.
If you encounter any difficulty in answering the tasks in this module, do not
hesitate to consult your teacher or facilitator. Always bear in mind that you are
not alone.
We hope that through this material, you will experience meaningful learning
and gain deep understanding of the relevant competencies. You can do it!
iv
Explore
Introduction:
A Sorting Algorithm is used to rearrange 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.
Sorting refers to the operation or technique of arranging and rearranging
sets of data in some specific order. A collection of records called a list where every
record has one or more fields. The fields which contain a unique value for each
record is termed as the key field. For example, a phone number directory can be
thought of as a list where each record has three fields - 'name' of the person,
'address' of that person, and their 'phone numbers'. Being unique phone number
can work as a key to locate any record in the list.
Sorting is the operation performed to arrange the records of a table or list in
some order according to some specific ordering criterion. Sorting is performed
according to some key value of each record.
The records are either sorted either numerically or alphanumerically. The records
are then arranged in ascending or descending order depending on the numerical
value of the key. Here is an example, where the sorting of a lists of marks obtained
by a student in any particular subject of a class.
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.
In other words, 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 takes an array as input and outputs a permutation of
that array that is sorted.
Subtask:
1. Identify the different sorting algorithms
2. Evaluate sorting algorithms
3. Demonstrate the sorting algorithms
4.
1
Learn
It always leads to a solution and tries to be the most efficient solution we can
think up. It's often a good idea to number the steps, but you don't have to. Instead
of numbered steps, some folks use indentation and write in pseudocode, which is a
semi-programming language used to describe the steps in an algorithm. But, we
won't use that here since simplicity is the main thing. Other folks just use a
diagram called a flowchart, which we will discuss soon.
2
Start
Input
Name, HrlyRate,
HrsWork, Deductn
Print
Name, GrossPay,
Netpay
End
3
Notice how the top of our example is just a numbered list of steps using plain
English, stating exactly what we want the procedure to do (no more, no less). The
bottom is the very same algorithm, but this time, we used shapes and arrows in a
flowchart (like a map of the route), so that a reader can visualize the journey.
That's a nice thing here, because in one of our steps (step 7) a decision must be
made and, depending on the result of that decision, our steps may not go in order
from start to end.
1. Step 1 is really just a reminder that this is a procedure with a beginning and an
end.
2. In step 2, we make a place in the computer to store what the user types in, also
called a variable
3. In step 3, we clear this variable because we might need to use it again and don't
want the old contents mixed in with the new.
6. In step 6, we tell our computer to take a close look at this email address-- is it
really an email address?
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.
4
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:
Best case
Worst case
Average case
Hence, 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 O (nlog n) to O(n2).
Bubble Sort
Insertion Sort
Insertion Sort
Merge Sort
5
Bubble Sort Algorithm
Bubble Sort is used 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.
Below given figure shows how Bubble Sort works:
6
Algorithm for Bubble Sort
1. algorithm Insertion_sort(list)
2. Pre: list 6= fi
3. Post: list has been sorted into values of ascending order
4. unsorted <- 1
5. while unsorted < list.Count
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
7
Example of Insertion Sort in Programming:
#include <iostream>
#include <conio.h>
int main()
{
int a[16], i, j, k, tmp;
cout << "enter the number of elements\n";
for (i = 0; i < 6; i++) { cin >> a[i];
}
for (i = 1; i < 6; i++) { for (j = i; j >= 1; j--) {
if (a[j] < a[j - 1]) {
tmp = a[j];
a[j] = a[j - 1];
a[j - 1] = tmp;
}
else
break;
}
}
cout << "sorted array\n" << endl;
for (k = 0; k < 6; k++) {
cout << a[k] << "\t";
}
8
*Output of the insertion sort in programming
9
Example of selection sort in programming:
#include <iostream>
using namespace std;
int main()
{
int a[100], i, n, p, k, min, loc, tmp;
tmp = a[p];
a[p] = a[loc];
a[loc] = tmp;
}
cout << "\nAfter Sorting: \n";
for (i = 1; i <= n; i++) {
cout << a[i] << endl;
}
}
10
Output:
Merge sort can be done in two types both having similar logic and way of
implementation. These are:
11
Below given figure shows how Merge Sort works:
1. algorithm Merge_Sort(list)
2. Pre: list 6= fi
3. Post: list has been sorted into values of ascending order
4. if list.Count = 1 // when already sorted
5. return list
6. end if
7. m <- list.Count = 2
8. left <- list(m)
9. right <- list(list.Count - m)
10.for i <- 0 to left.Count - 1
11.left[i] <- list[i]
12.end for
13.for i <- 0 to right.Count -1
14.right[i] <- list[i]
15.end for
16.left <- Merg_Sort(left)
17.right <- Merge_Sort(right)
18.return MergeOrdered(left, right)
12
19.end Merge_Sort
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? 15,20,10,18
A. 10 B. 2 C. 5 D. 25
4. What is the max. number of comparisons that can take place when a bubble sort
is implemented? Assume there are n elements in the array?
5. What are the worst case and best case time complexity of bubble sort
consequently?
13
Apply
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
14
Assess
Instructions: Solve the following and write your answer on 1 whole piece of
paper.
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
Guide Questions:
1. How important is the sorting algorithm?
2. Which algorithm finds you the easiest way? Why?
15
Answer Key
Engage
1. A
2. D
3. A
4. C
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
16
Assess:
References
17
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.
18
For inquiries or feedback, please write or call:
19