Arrays

Computer Science AS · Data types and structures. The idea in plain words, the rules to remember, the mistake to avoid and a worked example, written and checked by Mega Lecture.

Test this topic freeAll Computer Science AS topics

The idea

An array stores many values of the same data type under one identifier. Each value is an element and its position is its index. The lowest index is the lower bound and the highest is the upper bound. A 1D array is a list. A 2D array is a table of rows and columns, so it needs two indexes.

A linear search checks each element in turn from the start, until the item is found or the end is reached. The data does not need to be sorted.

A bubble sort compares neighbouring pairs and swaps a pair that is in the wrong order. After each pass the largest value not yet placed has moved to its final position, so the next pass can be one comparison shorter.

In simpler words

An array holds many values of the same type under one name. Each value has a position number, called its index. A 2D array is like a table, with rows and columns. A linear search checks each item in turn from the start. A bubble sort compares pairs next to each other and swaps them if they are in the wrong order. It repeats until sorted.

An everyday comparison

A bubble sort is like lining up children by height: you walk along comparing neighbours and swapping any pair in the wrong order. After one walk the tallest child has reached the end. The comparison stops working because children can see the whole line, while the algorithm only ever compares two neighbouring values, and a swap needs a temporary variable to avoid losing one value.

Rules to remember

Common mistake

Giving the fully sorted list as the result of the first pass. One pass only guarantees that the largest value is at the end, so follow the swaps pair by pair.

In the exam

Declare arrays with bounds and type, e.g. ARRAY[1:30] OF INTEGER, and for 2D give row then column. Calculate the size as upper bound minus lower bound plus 1. For a linear search, loop through elements until found or the end is reached. For a bubble sort, use nested loops, swap with a temporary variable and add a Swapped flag to stop early. When tracing, follow each pass pair by pair and show the list after each pass.

Worked example

An array holds 7, 3, 9, 2, 6. What is the order after the first pass of a bubble sort into ascending order?

  1. Compare 7 and 3: wrong order, swap. The array is now 3, 7, 9, 2, 6.
  2. Compare 7 and 9: correct order, no swap.
  3. Compare 9 and 2: swap. The array is now 3, 7, 2, 9, 6.
  4. Compare 9 and 6: swap. The array is now 3, 7, 2, 6, 9.

Answer: 3, 7, 2, 6, 9 (4 comparisons, 3 swaps, and 9 is now in its final place)

Ask about this

Type what you are stuck on. The helper finds the explanation, worked examples and the notes to read, free and instant.

Keep going

← Data types and recordsFiles →Take a Computer Science AS test