Resources | Subject Notes | Computer Science
Algorithms are step-by-step procedures for solving a problem. This section focuses on two fundamental sorting algorithms: Insertion Sort and Bubble Sort. These algorithms are often used for educational purposes due to their simplicity, although they are not the most efficient for large datasets.
Insertion Sort is a simple sorting algorithm that builds the final sorted array one item at a time. It iterates through the input array, taking each element and inserting it into its correct position in the already sorted portion of the array.
function insertionSort(array) for i from 1 to length(array) - 1 do key = array[i] j = i - 1 while j >= 0 and array[j] > key do array[j + 1] = array[j] j = j - 1 end while array[j + 1] = key end for
Consider the array: {5, 2, 4, 6, 1, 3}
The Insertion Sort process would be:
The time complexity of Insertion Sort is:
Bubble Sort is another simple sorting algorithm that repeatedly steps through the list, compares adjacent elements and swaps them if they are in the wrong order. The largest element "bubbles" to the end of the list with each pass.
The algorithm performs multiple passes over the list. In each pass, it compares adjacent elements and swaps them if they are in the wrong order. The largest element in the unsorted portion of the list "bubbles" to its correct position at the end of the unsorted portion.
function bubbleSort(array) n = length(array) for i from 0 to n - 2 do for j from 0 to n - i - 2 do if array[j] > array[j + 1] then swap(array[j], array[j + 1]) end if end for end for
Consider the array: {5, 2, 4, 6, 1, 3}
The Bubble Sort process would be:
The time complexity of Bubble Sort is:
Feature | Insertion Sort | Bubble Sort |
---|---|---|
Approach | Builds sorted subarray incrementally | Repeatedly swaps adjacent elements |
Number of Swaps | Generally fewer swaps | Potentially many swaps |
Performance | More efficient for nearly sorted arrays | Less efficient overall |
Space Complexity | $O(1)$ - In-place sorting | $O(1)$ - In-place sorting |
Both Insertion Sort and Bubble Sort are simple to understand and implement. However, their $O(n^2)$ time complexity makes them inefficient for large datasets. More advanced sorting algorithms like Merge Sort and Quick Sort offer significantly better performance for larger inputs.