2074 9

CSC211 ยท 2074 ยท 5 marks

What do you mean by sorting? Explain the Bubble sort with example.

What do you mean by sorting? Explain the Bubble sort with example. [5]

Data Structures and AlgorithmsChapter 6: SortingComparison Sorting Algorithms

Quick answer

Sorting is the process of arranging data elements in a specific order (either ascending or descending) so that the data can be searched, accessed, or processed more efficiently. Sorting organizes a collection of data into a sequence ordered by some criterion.

Sorting and Bubble Sort

What is Sorting?

Example: Arranging [5, 2, 8, 1, 9] into [1, 2, 5, 8, 9] (ascending order).


Bubble Sort

Definition: Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping adjacent elements if they are in the wrong order. The basic idea is to pass through the array sequentially several times. Each pass consists of comparing each element a[i] with its adjacent element a[i+1] and interchanging them if they are not in proper order.

After each pass, the largest unsorted element "bubbles up" to its correct position at the end of the array.

Algorithm

for i = 0 to n-2:
    for j = 0 to n-2-i:
        if a[j] > a[j+1]:
            swap(a[j], a[j+1])

Time Complexity

CaseComplexity
Best CaseO(n^2)
Average CaseO(n^2)
Worst CaseO(n^2)

Worked Example

Array: [5, 3, 8, 1, 4]

Pass 1 (i = 0)

StepComparisonArray State
j=05 > 3? Yes, swap[3, 5, 8, 1, 4]
j=15 > 8? No[3, 5, 8, 1, 4]
j=28 > 1? Yes, swap[3, 5, 1, 8, 4]
j=38 > 4? Yes, swap[3, 5, 1, 4, 8]

Largest element 8 is now at its correct position.

Pass 2 (i = 1)

StepComparisonArray State
j=03 > 5? No[3, 5, 1, 4, 8]
j=15 > 1? Yes, swap[3, 1, 5, 4, 8]
j=25 > 4? Yes, swap[3, 1, 4, 5, 8]

Second largest element 5 is now at its correct position.

Pass 3 (i = 2)

StepComparisonArray State
j=03 > 1? Yes, swap[1, 3, 4, 5, 8]
j=13 > 4? No[1, 3, 4, 5, 8]

Pass 4 (i = 3)

StepComparisonArray State
j=01 > 3? No[1, 3, 4, 5, 8]

Final Sorted Array

[1, 3, 4, 5, 8]

Summary

  • Bubble sort is simple but inefficient for large datasets due to O(n^2) complexity.
  • It performs a maximum of n-1 passes for an array of n elements.
  • It is an in-place sorting algorithm (no extra memory required).

Short on time? The 1, 5 and 10 mark versions of this answer, flashcards and practice sets come with a program pass.