📑 Contents

Chapter 10.2: Arrays, Searching & Sorting Algorithms

9618 AS Computer Science

📚 Learning Objectives
📋 Prior Knowledge Required
🌟 Did You Know?

In a variable, typically only one value can be stored at a time. Storing a new value replaces the old one. However, arrays allow us to store multiple values in a single variable! Each value is assigned a unique index number for easy access.

95 100 56 78 42 [1] [2] [3] [4] [5] scores Variable: 95 score

1. One-Dimensional (1D) Arrays

A 1D array is a data structure containing several elements of the same data type. These elements can be accessed using the same identifier name. The position of each element in an array is identified using the array's index (also called subscript).

📖 Key Terminology

1.1 Declaring a 1D Array

When a 1D array is declared in pseudocode, the lower bound (LB), upper bound (UB) and data type are included:

DECLARE : ARRAY [LB:UB] OF // Example: Declare an array named "numbers" with 5 integers DECLARE numbers : ARRAY [1:5] OF INTEGER // Example: Declare an array for 10 names DECLARE names : ARRAY [0:9] OF STRING
💡 Exam Tip

Pay attention to whether the lower bound is 0 or 1! An array declared as ARRAY[0:4] has 5 elements (indices 0,1,2,3,4), while ARRAY[1:5] also has 5 elements (indices 1,2,3,4,5).

1.2 Initializing Array Elements

Arrays can be initialized during declaration or later in the program. Each element is assigned a value using its index:

// Declaring and initializing an array DECLARE numbers : ARRAY [1:5] OF INTEGER numbers[1] ← 11 numbers[2] ← 120 numbers[3] ← 130 numbers[4] ← 404 numbers[5] ← 500
Memory representation of "numbers" array: 11 120 130 404 500 [1] [2] [3] [4] [5]

2. Inputting and Outputting Array Values

2.1 Inputting Values into an Array

To input values into an array from user input, we use a loop to iterate through each element. The loop counter serves as the array index:

// Input values into an array DECLARE numbers : ARRAY [1:5] OF INTEGER FOR i ← 1 TO 5 OUTPUT "Enter number ", i, ":" INPUT numbers[i] NEXT i

2.2 Outputting Values from an Array

To output values from an array, we iterate through each element using the loop counter as the index:

// Output all values from an array FOR i ← 1 TO 5 OUTPUT numbers[i] NEXT i
📝 Complete Example: Input and Output
DECLARE numbers : ARRAY [1:5] OF INTEGER // Input values FOR i ← 1 TO 5 OUTPUT "Enter number ", i, ":" INPUT numbers[i] NEXT i OUTPUT "Numbers entered:" // Output values FOR i ← 1 TO 5 OUTPUT numbers[i] NEXT i

2.3 Finding the Sum of Array Elements

A common operation is to calculate the sum of all elements in an array:

DECLARE numbers : ARRAY [1:5] OF INTEGER DECLARE totalSum : INTEGER // Input values... FOR i ← 1 TO 5 OUTPUT "Enter value for position ", i INPUT numbers[i] NEXT i // Calculate sum totalSum ← 0 FOR i ← 1 TO 5 totalSum ← totalSum + numbers[i] NEXT i OUTPUT "The total sum is: ", totalSum

2.4 Finding Negative Values in an Array

We can use an IF statement inside a loop to check each element:

DECLARE numbers : ARRAY [1:5] OF INTEGER // Input values... FOR i ← 1 TO 5 OUTPUT "Enter value for position ", i INPUT numbers[i] NEXT i OUTPUT "Negative Values:" FOR i ← 1 TO 5 IF numbers[i] < 0 THEN OUTPUT numbers[i] ENDIF NEXT i
Array Processing Flow Start FOR i=1 to 5 Process[i] NEXT i End

3. Two-Dimensional (2D) Arrays

A 2D array can be referred to as a table, with rows and columns. It stores elements in a grid-like structure where each element is identified by its row and column indices.

📖 2D Array Declaration Syntax
DECLARE : ARRAY [LBR:UBR, LBC:UBC] OF // Where: // LBR = Lower Bound for Rows // UBR = Upper Bound for Rows // LBC = Lower Bound for Columns // UBC = Upper Bound for Columns

3.1 Declaring a 2D Array

// Declare a 2D array with 3 rows and 5 columns DECLARE matrix : ARRAY [1:3, 1:5] OF INTEGER
2D Array "matrix" - 3 rows × 5 columns Row 1 Row 2 Row 3 Col 1 Col 2 Col 3 Col 4 Col 5

3.2 Accessing Elements in a 2D Array

To access an element, use both row and column indices: array[row, column]

// Set value 1985 at row 2, column 4 matrix[2, 4] ← 1985 // Access element at row 2, column 3 DECLARE value : INTEGER value ← matrix[2, 3]
💡 Exam Tip

Remember: First index = Row, Second index = Column. Think of it like coordinates on a map - you go down (row) then across (column).

3.3 Using Nested Loops with 2D Arrays

To traverse all elements of a 2D array, use nested loops - one for rows and one for columns:

📝 Initialize 2D Array to Zero
DECLARE ThisTable : ARRAY [0:4, 0:2] OF INTEGER // Initialize all elements to zero FOR Row ← 0 TO 4 FOR Column ← 0 TO 2 ThisTable[Row, Column] ← 0 NEXT Column NEXT Row
📝 Output Contents of 2D Array
FOR Row ← 0 TO 4 FOR Column ← 0 TO 2 OUTPUT ThisTable[Row, Column] // stay on same line NEXT Column OUTPUT Newline // move to next line for next row NEXT Row

4. Advantages of Using Arrays

Why use arrays instead of separate variables? Consider this scenario: storing names for 40 students.

❌ Without Arrays (Inefficient)
DECLARE Name1 : STRING DECLARE Name2 : STRING DECLARE Name3 : STRING // ... 37 more declarations ... DECLARE Name40 : STRING OUTPUT "Input the name for student 1" INPUT Name1 OUTPUT "Input the name for student 2" INPUT Name2 // ... 38 more input statements ...
✅ With Arrays (Efficient)
DECLARE Name : ARRAY [1:40] OF STRING DECLARE Index : INTEGER FOR Index ← 1 TO 40 OUTPUT "Input the name for student ", Index INPUT Name[Index] NEXT Index
Advantage Explanation
Easier algorithms Searching and organizing data is simpler with indexed access
Loop-controlled access Values accessed via loop variable used as index
Easier to design & maintain Code is easier to design, amend, debug, test and understand
Fewer identifiers Single array name instead of multiple variable names; less storage required
🧠 Memory Trick: ARRAY Advantages

Remember ELF:

❌ Without Arrays ✓ With Arrays Name1, Name2, Name3... 40 separate variables 40 INPUT statements Name[1:40] 1 array declaration 1 loop for all inputs

5. Linear Search Algorithm

A linear search is a simple searching algorithm that checks each element in a list one by one until the target value is found or all elements have been checked.

📖 How Linear Search Works
  1. Start with the first value in the dataset
  2. Check if it is the value you are looking for - if yes, STOP!
  3. If not, move to the next value and check again
  4. Repeat until you find the value or reach the end
⚠️ Key Point

A linear search can be performed even if the values are not in order. This is different from binary search which requires sorted data.

5.1 Linear Search Pseudocode

📝 Linear Search Implementation
DECLARE MaxIndex, SearchValue, Index : INTEGER DECLARE Found : BOOLEAN DECLARE MyList : ARRAY [0:6] OF INTEGER MaxIndex ← 6 OUTPUT "Enter value you want to search:" INPUT SearchValue Found ← FALSE Index ← -1 REPEAT Index ← Index + 1 IF MyList[Index] = SearchValue THEN Found ← TRUE ENDIF UNTIL Found = TRUE OR Index >= MaxIndex IF Found = TRUE THEN OUTPUT "Value found at location: ", Index ELSE OUTPUT "Value not found" ENDIF
Linear Search: Looking for value 37 12 25 37 42 56 19 8 [0] [1] [2] [3] [4] [5] [6] Check 1 Check 2 Found! Search direction →
Identifier Data Type Description
MyList ARRAY[0:6] OF INTEGER Stores the list of numbers to search through
SearchValue INTEGER The number the user wants to search for
Found BOOLEAN Tracks whether the target value has been found
Index INTEGER Current position being checked in the array

6. Bubble Sort Algorithm

A bubble sort is a simple sorting algorithm that starts at the beginning of a dataset and checks values in 'pairs', swapping them if they are not in the correct order. One full run through is called a pass.

📖 How Bubble Sort Works
  1. Compare the first two values in the dataset
  2. If they are in the wrong order, swap them
  3. Compare the next two values
  4. Repeat until end of dataset (Pass 1 complete)
  5. If any swaps were made, repeat from the start (Pass 2, 3...)
  6. When no swaps are needed, the list is sorted!
💡 Why "Bubble" Sort?

The largest values "bubble up" to the end of the array with each pass, like bubbles rising to the surface of water!

Bubble Sort Example: Sorting [5, 2, 4, 1, 6, 3] Original: 5 2 4 1 6 3 Pass 1: 2 4 1 5 3 6 ← largest in place Pass 2: 2 1 4 3 5 6 Pass 3: 1 2 3 4 5 6 ← Sorted! 5↔2 swap 4↔1 swap 2↔1 swap

6.1 Bubble Sort Pseudocode

📝 Bubble Sort Implementation
DECLARE Numbers : ARRAY [0:5] OF INTEGER DECLARE Temp : INTEGER DECLARE n : INTEGER DECLARE NoMoreSwaps : BOOLEAN // Bubble sort algorithm n ← 5 REPEAT NoMoreSwaps ← TRUE FOR j ← 0 TO n - 1 IF Numbers[j] > Numbers[j + 1] THEN // Swap elements Temp ← Numbers[j] Numbers[j] ← Numbers[j + 1] Numbers[j + 1] ← Temp NoMoreSwaps ← FALSE ENDIF NEXT j n ← n - 1 // Don't check sorted positions UNTIL NoMoreSwaps = TRUE

7. Exam-Style Questions

1. Describe two features of an array. [2 marks]

Answer:

  • Contains multiple elements of the same data type
  • Each element is accessed using an index/subscript
  • Has a fixed size when declared
  • Elements stored in contiguous memory locations

Additional points for deeper understanding:

  • Lower bound indicates the first element index
  • Upper bound indicates the last element index
2. A program is being written to process student information. One task involves inputting names of all students in a class of 40. Re-write the pseudocode to perform this task efficiently. [4 marks]

Answer:

DECLARE Name : ARRAY [1:40] OF STRING DECLARE Index : INTEGER FOR Index ← 1 TO 40 OUTPUT "Input the name for student ", Index INPUT Name[Index] ENDFOR

Marking points:

  • Correct array declaration with appropriate bounds (1 mark)
  • Correct data type - STRING (1 mark)
  • FOR loop with correct range (1 mark)
  • Correct INPUT statement using index (1 mark)
3. Give two advantages of using arrays instead of separate variables. [2 marks]

Answer:

  • Program code is easier to read/modify/debug
  • Easier to access individual elements using index
  • Only single identifier used instead of multiple variable names
  • Can use loops to process all elements efficiently
  • Less storage required (fewer identifiers)
4. A 2D array ProductionData is declared as: DECLARE ProductionData : ARRAY[1:4, 1:3] OF INTEGER
(a) How many elements does this array contain? [1 mark]
(b) Give the value of ProductionData[3, 2] if row 3 contains: 15, 28, 19 [1 mark]

Answer (a):

  • 12 elements (4 rows × 3 columns = 12)

Answer (b):

  • 28 (Row 3, Column 2 = second value in row 3)
5. A programmer has started to write a program to find the maximum and minimum values stored in an array of 100 integers. Name a more appropriate loop structure for this task and justify your choice. [3 marks]

Answer:

  • FOR...NEXT loop (count-controlled loop) (1 mark)
  • Justification: Known/fixed number of iterations (1 mark)
  • All elements of the array need to be checked (1 mark)

Additional points for deeper understanding:

  • The loop counter can be used as the array index
  • More efficient than conditional loops for fixed iterations

7. Exam-Style Questions (Continued)

6. Write pseudocode to search for a specific value in a 1D array using linear search. The program should output the position if found, or "Not found" if not present. [6 marks]

Answer:

DECLARE MyList : ARRAY [0:6] OF INTEGER DECLARE SearchValue : INTEGER DECLARE Found : BOOLEAN DECLARE Index : INTEGER OUTPUT "Enter value to search:" INPUT SearchValue Found ← FALSE Index ← 0 WHILE Index <= 6 AND Found = FALSE DO IF MyList[Index] = SearchValue THEN Found ← TRUE ELSE Index ← Index + 1 ENDIF ENDWHILE IF Found = TRUE THEN OUTPUT "Value found at position: ", Index ELSE OUTPUT "Not found" ENDIF

Marking points:

  • Correct declarations (1 mark)
  • Input search value (1 mark)
  • Initialize Found flag and Index (1 mark)
  • Correct loop structure (1 mark)
  • Comparison with array element (1 mark)
  • Correct output statements (1 mark)
7. Describe the steps a bubble sort algorithm takes to sort an array into ascending order. [4 marks]

Answer:

  • Compare adjacent elements starting from the first pair (1 mark)
  • If they are in the wrong order, swap them (1 mark)
  • Continue through the array until all pairs have been checked - this is one pass (1 mark)
  • Repeat passes until no swaps are needed, indicating the list is sorted (1 mark)

Additional points for deeper understanding:

  • After each pass, the largest unsorted element "bubbles" to its correct position
  • The number of comparisons needed decreases with each pass
  • An optimization: stop early if no swaps were made in a pass
8. Write pseudocode to output the contents of a 2D array named "Grid" with dimensions [0:2, 0:4] in a table format. [5 marks]

Answer:

DECLARE Grid : ARRAY [0:2, 0:4] OF INTEGER DECLARE Row, Column : INTEGER FOR Row ← 0 TO 2 FOR Column ← 0 TO 4 OUTPUT Grid[Row, Column], " " // stay on same line NEXT Column OUTPUT NewLine // move to next line NEXT Row

Marking points:

  • Correct outer loop for rows (1 mark)
  • Correct inner loop for columns (1 mark)
  • Correct array indexing [Row, Column] (1 mark)
  • Output stays on same line inside inner loop (1 mark)
  • New line after each row (1 mark)
9. Explain why a linear search does not require the data to be sorted, unlike a binary search. [3 marks]

Answer:

  • Linear search checks each element one by one in order (1 mark)
  • It does not make any assumptions about the position of elements (1 mark)
  • Binary search requires sorted data to eliminate half the remaining elements with each comparison (1 mark)

Additional points for deeper understanding:

  • Linear search has O(n) time complexity - checks all n elements in worst case
  • Binary search has O(log n) time complexity - much faster for large sorted datasets
  • Linear search is simpler to implement and works on any data
10. Write pseudocode to find the sum of all elements in a 1D array called "Values" with 10 elements. [4 marks]

Answer:

DECLARE Values : ARRAY [1:10] OF INTEGER DECLARE Total : INTEGER DECLARE i : INTEGER Total ← 0 FOR i ← 1 TO 10 Total ← Total + Values[i] NEXT i OUTPUT "Sum is: ", Total

Marking points:

  • Initialize Total to 0 (1 mark)
  • Correct loop structure (1 mark)
  • Correct addition: Total + Values[i] (1 mark)
  • Output the result (1 mark)

7. Exam-Style Questions (Continued)

11. Write pseudocode to initialize all elements of a 2D array called "Table" with dimensions [0:4, 0:2] to the value 0. [4 marks]

Answer:

DECLARE Table : ARRAY [0:4, 0:2] OF INTEGER DECLARE Row, Column : INTEGER FOR Row ← 0 TO 4 FOR Column ← 0 TO 2 Table[Row, Column] ← 0 NEXT Column NEXT Row

Marking points:

  • Correct nested loop structure (2 marks)
  • Correct indices [Row, Column] (1 mark)
  • Assignment to 0 (1 mark)
12. A company stores daily sales figures for 5 products over 7 days in a 2D array. Write the declaration statement for this array. [2 marks]

Answer:

DECLARE Sales : ARRAY [1:5, 1:7] OF INTEGER // OR DECLARE Sales : ARRAY [1:7, 1:5] OF INTEGER

Note: Either orientation is acceptable as long as it's consistent with the program logic.

  • Correct keyword DECLARE (1 mark)
  • Correct dimensions and data type (1 mark)
13. Explain what happens during one "pass" of a bubble sort algorithm. [3 marks]

Answer:

  • Each pair of adjacent elements is compared from left to right (1 mark)
  • If elements are in the wrong order, they are swapped (1 mark)
  • At the end of the pass, the largest unsorted element is in its correct position (1 mark)

Additional points for deeper understanding:

  • After k passes, k largest elements are in their correct positions
  • The number of comparisons decreases with each pass

8. Glossary

📖 Key Terms
Term Definition
Array A data structure that stores multiple elements of the same data type, accessed using a common identifier and index
Index/Subscript A number that identifies the position of an element within an array
Lower Bound The index of the first element in an array
Upper Bound The index of the last element in an array
1D Array A linear array with one dimension; can be thought of as a list with rows
2D Array An array with two dimensions; can be thought of as a table with rows and columns
Linear Search A search algorithm that checks each element in order until the target is found or the end is reached
Bubble Sort A sorting algorithm that repeatedly compares adjacent elements and swaps them if they are in the wrong order
Pass One complete iteration through an array during a sorting algorithm
Swap Exchanging the values of two variables or array elements
Nested Loop A loop inside another loop; used for traversing 2D arrays
Element A single value stored at a specific position in an array
Traversal The process of visiting each element in an array exactly once
Contiguous Memory Memory locations that are adjacent to each other; arrays store elements in contiguous memory

9. Exam Success Tips (Part 1)

💡 Array Declaration Tips
💡 2D Array Tips
💡 Linear Search Tips
💡 Bubble Sort Tips
🧠 Memory Trick: Swapping Two Values

Remember the "Three-Cup Shuffle":

Temp ← A // Pour A into temp cup A ← B // Pour B into A B ← Temp // Pour temp into B

9. Exam Success Tips (Part 2)

❌ Common Mistakes to Avoid
⚠️ Always Check These in Exam
💡 Answer Structure Tips
Quick Reference: Array Operations 1D Array DECLARE A[1:5] Access: A[i] One loop needed 2D Array DECLARE A[1:3,1:4] Access: A[row,col] Nested loops needed Search & Sort Linear: O(n) Bubble: O(n²) Use Boolean flags

10. Key Takeaways

📌 Summary Points

Arrays

1D vs 2D Arrays

Searching & Sorting

Advantages of Arrays

🌟 Remember for the Exam!
Chapter 10.2 Summary ARRAYS 1D & 2D Search & Sort Loops & Operations