Computer Science  ·  Level 6
Algorithms And Data Structures
Chapter 6: Sorting Techniques
📚 4 Topics
⚑ What you will be able to do

By the end of this chapter, you will be able to:

  • Explain clearly what sorting means and why it is important in organizing data.
  • Identify and apply different categories of sorting techniques correctly.
  • Use various types of sorting algorithms effectively to arrange data.
  • Demonstrate sorting algorithms in C++ while following correct coding practices.

Mastering these skills will help you organize data efficiently, which is essential for solving real-world problems in programming and technology.

6.1 Definition of Sorting

Sorting is the process of arranging the items in a collection into a defined order, according to a rule that can be applied to every pair of items. The rule may place numbers from smallest to largest, names alphabetically, or dates from earliest to latest. Example: a SACCO keeps the records of its members in a list, and arranging them by member number lets the clerk find any member quickly instead of reading every record from the beginning.

In computing, sorting is carried out on data held in structures such as arrays and lists. A sorting algorithm is a finite, step-by-step set of instructions that compares items and rearranges them until the whole collection satisfies the chosen order.

Ascending and descending order

Every sort has a direction. Ascending order places the smallest or earliest item first and the largest or latest item last, while descending order does the opposite. The direction is chosen according to the need: a list of fee arrears may be most useful with the largest balance first, whereas a register is most useful in alphabetical order.

Example: the numbers 45, 12, 78, 23 are arranged as follows.

Ascending: 12, 23, 45, 78

Descending: 78, 45, 23, 12

Data type Ascending order Descending order
Numbers 5, 9, 14, 30 30, 14, 9, 5
Text Achieng, Kamau, Wanjiru Wanjiru, Kamau, Achieng
Dates 02/01/2024, 15/03/2024, 30/09/2024 30/09/2024, 15/03/2024, 02/01/2024
Money Ksh 500, Ksh 2,000, Ksh 12,500 Ksh 12,500, Ksh 2,000, Ksh 500

Basic terms used in sorting

A few terms appear in every discussion of sorting. Understanding them makes it easier to read and write sorting algorithms.

Example: a secondary school stores each student as a record containing the admission number, the name and the mean mark. Sorting the records by mean mark produces a ranking, while sorting by name produces an alphabetical class list from the same data.

  • Collection: the group of items to be sorted, usually stored in an array or a list.
  • Record: a single item made up of one or more fields, such as a student with an admission number, a name and a mark.
  • Key: the field on which the order is based. Sorting students by mean mark uses the mean mark as the key.
  • Comparison: the test that decides which of two items should come first, for example checking whether one key is greater than another.
  • Swap: the exchange of the positions of two items in the collection, which is the basic way in which items are moved into place.
  • Pass: one complete scan through the collection during which comparisons and swaps are made.

Why sorting is important

Sorted data is easier for people to read and much faster for computers to search. Many everyday systems depend on sorted data, and sorting is one of the most frequently performed operations in programming.

  • Faster searching: a sorted list can be searched using binary search, which repeatedly halves the portion being examined. A county land registry with sorted plot numbers can locate a plot in a few steps instead of checking every entry.
  • Easier reading and reporting: a bank statement is arranged by transaction date so that a customer can follow the movement of money from the first entry to the last.
  • Scheduling and priority: a hospital arranges its appointments by time so that the reception desk and the doctors see patients in the correct sequence.
  • Ranking and selection: a logistics company can sort deliveries by distance or by weight to decide which should be dispatched first.
  • Finding duplicates and gaps: when records are sorted, identical or missing entries sit next to each other. A hotel sorting bookings by room number and check-in date can quickly spot two guests booked into the same room on the same night.
  • Supporting other algorithms: merging lists, removing duplicates and grouping records all work more simply and efficiently when the data is already in order.

Sorting different kinds of data

Sorting rules depend on the type of data being compared. A programmer must choose a rule that matches the data, otherwise the result may look correct to the computer but wrong to the user.

Example: a supermarket sorts its stock list by unit price in Ksh, then by product name, so that items with the same price appear in alphabetical order.

  • Numbers: compared by value, so 9 comes before 30. If numbers are stored as text, they are compared character by character and "30" would wrongly come before "9".
  • Text: compared character by character using the character codes of the computer. In many systems all capital letters come before small letters, so "Zawadi" would appear before "achieng" unless the case is ignored.
  • Dates: compared by year first, then month, then day. Storing dates in a year-month-day format makes this comparison straightforward.
  • Records with several keys: the primary key is compared first, and the secondary key is used only when the primary keys are equal. A school may sort by class and then by mean mark within each class.
  • Mixed or missing values: blank entries and special values need a clear rule, such as placing them at the end of the list.

Requirements of a correctly sorted result

A sorting algorithm is correct only when its output satisfies two conditions. First, the items must be in the required order, so that every item comes before or equal to the item that follows it in the chosen direction. Second, the output must contain exactly the same items as the input, with none lost, added or changed. For example, if a list of five loan amounts is sorted, the result must still contain those same five amounts, now arranged from smallest to largest.

The rest of this chapter
🔒

Create a free account to open more of this chapter.

Free: practical guides, quick cards, workplace scenarios and more.

Create a free account
🔒6.2 Categories of sorting

Sorting algorithms can all put data in order, but they differ in how they treat equal values, how they react to data that is already partly ordered, and how much extra memory they need. These differences let us place every algorithm into categories, and each c…

🔒6.3 Types of Sorting algorithms

Many different procedures exist for arranging data in order, and they differ in how they compare items, how they move them and how much work they do as the list grows. Bubble sort, insertion sort and selection sort are the three basic comparison-based methods…

🔒6.4 Demonstration of sorting algorithms using C++

Once the ideas behind bubble, insertion and selection sort are understood, the next step is to turn them into working programs. C++ is well suited to this because it gives direct control over arrays, loops and element comparisons, which are the building blocks…

Chapter Practical Activities

Practical 1: Implementation of Bubble Sort Algorithm in C++

Computer Science · Level 6
Algorithms And Data Structures
PRACTICAL ASSESSMENT
TIME: 4 HOURS
⬇ PDFCandidate Instructions (Candidate Tool)

Type: Individual

INSTRUCTIONS TO CANDIDATE:
1.  You are required to perform the following task:
i.  Write and execute a C++ program that sorts an array of 15 integers using the Bubble Sort algorithm as per the provided specification.
2.  You have been provided with the following resources for the practical task:
Tools & EquipmentMaterials
Working computerPlain papers
C++ IDE
⬇ PDFResources Required (Cutting List)
S/NItemQuantity
1Working computer1 Pc per Candidate
2C++ IDE (e.g., Code::Blocks, Visual Studio, Dev-C++)1 Pc per Candidate
3Plain papers2 Pcs per Candidate
⬇ PDFAssessor Guide
Items to be EvaluatedMarks AvailableMarks ObtainedComments
TASK 1: Implement Bubble Sort
Observed computer laboratory rules
(Award 2 marks or zero)
2
Launched C++ IDE successfully
(Award 2 marks or zero)
2
Declared an integer array of size 15
(Award 2 marks or zero)
2
Captured input of 15 integers into the array
(Award 1 mark for each 5 inputs correctly captured or zero)
3
Implemented Bubble Sort algorithm correctly with nested loops
(Award 4 marks for outer loop, 4 marks for inner loop and swap logic)
8
Swapped elements correctly to sort in ascending order
(Award 5 marks for correct swap implementation or zero)
5
Displayed the sorted array output correctly
(Award 3 marks or zero)
3
Compiled, debugged, and executed the program without errors
(Award 5 marks or zero)
5
Commented code appropriately for readability
(Award 1 mark for each relevant comment or zero)
2
Sub-Total32
PRODUCT CHECKLIST
Program sorts the array of 15 integers correctly in ascending order
(Award 10 marks for correct and complete sorting output or zero)
10
Output is formatted neatly and clearly displayed on screen
(Award 3 marks or zero)
3
Sub-Total13
GRAND TOTAL45
ASSESSMENT OUTCOME:   ☐ Competent    ☐ Not Yet Competent (competent if at least 50%)

Practical 2: Implement Selection Sort to Sort a List of 15 Integers

Computer Science · Level 6
Algorithms And Data Structures
PRACTICAL ASSESSMENT
TIME: 4 HOURS
⬇ PDFCandidate Instructions (Candidate Tool)

Type: Individual

INSTRUCTIONS TO CANDIDATE:
1.  You are required to perform the following task:
i.  Write and execute a C++ program that implements Selection Sort to sort an array of 15 integers and display the sorted list.
2.  You have been provided with the following resources for the practical task:
Tools & EquipmentMaterials
A working computerTwo plain papers
C++ IDE
⬇ PDFResources Required (Cutting List)
S/NItemQuantity
1A working computer1 Pc per Candidate
2C++ IDE (e.g. Code::Blocks or Visual Studio)1 Pc per Candidate
3Two plain papers2 Pcs per Candidate
⬇ PDFAssessor Guide
Items to be EvaluatedMarks AvailableMarks ObtainedComments
TASK 1: Implement Selection Sort
Observed computer laboratory rules
(Award 2 marks or zero)
2
Launched C++ IDE correctly
(Award 1 mark or zero)
1
Declared an integer array of size 15
(Award 2 marks or zero)
2
Captured 15 integer elements into the array
(Award 1 mark for each 5 elements correctly captured)
3
Implemented the Selection Sort algorithm correctly
(Award marks based on correct implementation of selection, swapping, and iteration)
10
Displayed the sorted array output correctly
(Award 5 marks for correct and clear display of sorted elements)
5
Commented code appropriately for readability
(Award 1 mark for each relevant comment, max 3)
3
Compiled, debugged, and executed the program without errors
(Award 4 marks or zero)
4
Sub-Total30
PRODUCT CHECKLIST
Sorted array output is correct and matches ascending order for the 15 integers
(Award 10 marks for correct sorted output matching Selection Sort results)
10
Code structure is well organized with proper indentation and naming conventions
(Award 5 marks for neat and professional code layout)
5
Program runs to completion without runtime or logical errors
(Award 5 marks for error-free execution)
5
Sub-Total20
GRAND TOTAL50
ASSESSMENT OUTCOME:   ☐ Competent    ☐ Not Yet Competent (competent if at least 50%)
🔒

Free: practical guides, quick cards, workplace scenarios and more.

Create a free account
🔒Implement Insertion Sort Algorithm in C++Practical 3
🔒Implement Merge Sort Algorithm to Sort a List of 20 IntegersPractical 4
🔒Implement Quick Sort Algorithm to Sort a List of 20 IntegersPractical 5
🔒Performance Comparison of Sorting Algorithms on a Data SetPractical 6
🔒Draw and Explain Bubble Sort Algorithm StepsPractical 7
🔒Sort an Array of Strings Alphabetically Using a Sorting AlgorithmPractical 8
🔒Sort Student Records by Admission Number Using Bubble SortPractical 9
🔒Demonstrate Stability in Sorting Using Stable and Unstable AlgorithmsPractical 10
Am I competent?

At the start of this chapter we promised you would be able to:

  • Explain clearly what sorting means and why it is important in organizing data.
  • Identify and apply different categories of sorting techniques correctly.
  • Use various types of sorting algorithms effectively to arrange data.
  • Demonstrate sorting algorithms in C++ while following correct coding practices.

Tick each one you can genuinely do.

So, are you there yet?

You're competent when you can confidently do 50% or more of what this chapter promised.

Sign in to record how you're doing.