Contact Form

Name

Email *

Message *

Cari Blog Ini

Bubble Sort Worst Case

Bubble Sort, Selection Sort, and Insertion Sort: A Comprehensive Guide

Overview

Bubble Sort, Selection Sort, and Insertion Sort are simple yet efficient sorting algorithms that are widely used to sort small datasets or serve as building blocks for more complex sorting techniques.

Bubble Sort

Bubble Sort operates by repeatedly comparing adjacent elements and swapping them if they are out of order. The algorithm continues iterating through the array until no more swaps are necessary. The worst-case scenario for Bubble Sort occurs when the array elements are arranged in decreasing order, resulting in a time complexity of O(n^2), where n is the number of elements in the array.

Example:

Consider an array [5, 4, 3, 2, 1]. * Iteration 1: Compare 5 and 4, swap to obtain [4, 5, 3, 2, 1]. * Iteration 2: Compare 5 and 3, swap to obtain [4, 3, 5, 2, 1]. * Iteration 3: Compare 5 and 2, swap to obtain [4, 3, 2, 5, 1]. * Iteration 4: Compare 5 and 1, swap to obtain [4, 3, 2, 1, 5]. * Iteration 5: No swaps are necessary, the array is sorted.

Selection Sort

Selection Sort finds the minimum element from the unsorted portion of the array and swaps it with the first element of that portion. This process is repeated until the entire array is sorted. The worst-case time complexity of Selection Sort is also O(n^2).

Example:

Consider an array [5, 4, 3, 2, 1]. * Iteration 1: Find the minimum element (1) and swap it with the first element to obtain [1, 4, 3, 2, 5]. * Iteration 2: Find the minimum element (2) in the remaining unsorted portion and swap it with the second element to obtain [1, 2, 4, 3, 5]. * Iteration 3: Find the minimum element (3) in the remaining unsorted portion and swap it with the third element to obtain [1, 2, 3, 4, 5]. * Iteration 4: Find the minimum element (4) in the remaining unsorted portion and swap it with the fourth element to obtain [1, 2, 3, 4, 5]. * Iteration 5: No swaps are necessary, the array is sorted.

Insertion Sort

Insertion Sort builds the sorted array one element at a time by inserting each unsorted element into its correct position in the sorted portion of the array. The worst-case time complexity of Insertion Sort is also O(n^2).

Example:

Consider an array [5, 4, 3, 2, 1]. * Iteration 1: Insert 4 into the sorted portion to obtain [4, 5]. * Iteration 2: Insert 3 into the sorted portion to obtain [3, 4, 5]. * Iteration 3: Insert 2 into the sorted portion to obtain [2, 3, 4, 5]. * Iteration 4: Insert 1 into the sorted portion to obtain [1, 2, 3, 4, 5].

Conclusion

Bubble Sort, Selection Sort, and Insertion Sort are simple and versatile sorting algorithms that are often used for educational purposes or to sort relatively small datasets. Their worst-case time complexity of O(n^2) makes them less efficient for sorting large arrays, but their simplicity and ease of implementation make them valuable tools in specific scenarios.


Comments