Coventry University Logo
4061CEM - Programming and Algorithms 1
  • Sorting Algorithms
    3

Sorting Algorithms

Before you attempt this activity, it is best that you review lecture video one from week eleven. You can find the video and slides on the module page.

For this activity you will be using the integrated development environment recommended by the module leader. If you need to set up your development environment, it is recommended that you check out the instructions from activity four of week one.

Are You Struggling?

If you have trouble with any of the tasks or want to check your answers are correct, then please make yourself known to a member of staff.

What is Pseudocode?

Pseudocode is a universal, formal syntax which is used to describe an algorithm, or a collection of algorithms. It can be used to describe the entire execution of an algorithm. It will use terminology that is close to existing programming languages, so it feels natural to you whilst reading and writing.

Task 1

For this task you need to write a function that will sort a given list of numbers using Bubble Sort, for example:

[5, 2, 7, 9, 0, 1]

The function should return to the user the sorted list in ascending order, for example:

[0, 1, 2, 5, 7, 9]

To assist you in the implementation of the algorithm, pseudocode is provided below for Bubble Sort.

BUBBLE_SORT(A)
    swap  TRUE
    WHILE swap is TRUE:
        swap  FALSE
    FOR i  0 to length(A) - 1
    IF A[i] > A[i + 1]
        swap  TRUE
        SWAP(A[i], A[i + 1])

If you require further assistance with this algorithm, then you may want to read up on Bubble Sort.

Task 2

For this task you need to write a function that will sort a given list of numbers using merge sort, for example:

[5, 2, 7, 9, 0, 1]

The function should return to the user the sorted list in ascending order, for example:

[0, 1, 2, 5, 7, 9]

To assist you in the implementation of the algorithm, pseudocode is provided below for Merge Sort. If you require further assistance with this algorithm, then you may want to read up on Merge Sort.

MERGE_SORT(L):
    IF length(L) <= 1
        RETURN L
    a  L[0..length(L / 2]
    b L [length(L) / 2..length(L)]
    a  MERGE - SORT(a)
    b  MERGE - SORT(b)
    RETURN MERGE(a, b)
MERGE(a,b):
out  arrayof length(length(a)+length(b))
i  0
j  0
FOR x  0 TO length(out)
    IF a[i] < b[j]
        out[x]  a[i]; i++
    ELSE
        out[x]  b[j]; j++