ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

Bubble Sort Implementation

Kotlin

Goal -- WPM

Ready
Exercise Algorithm Area
1fun bubbleSort(arr: IntArray) {
2val n = arr.size
3if (n <= 1) {
4// No sorting needed for arrays with 0 or 1 element
5return
6}
7
8var swapped: Boolean
9for (i in 0 until n - 1) {
10swapped = false
11// Last i elements are already in place
12for (j in 0 until n - 1 - i) {
13// Traverse the array from 0 to n-i-1
14// Swap if the element found is greater than the next element
15if (arr[j] > arr[j + 1]) {
16// Swap arr[j] and arr[j+1]
17val temp = arr[j]
18arr[j] = arr[j + 1]
19arr[j + 1] = temp
20swapped = true
21}
22}
23
24// If no two elements were swapped by inner loop, then break
25// This optimization makes it adaptive for already sorted arrays
26if (!swapped) {
27break
28}
29}
30}
Algorithm description viewbox

Bubble Sort Implementation

Algorithm description:

This function implements the Bubble Sort algorithm to sort an array of integers in ascending order. It repeatedly steps through the list, compares adjacent elements and swaps them if they are in the wrong order. The pass through the list is repeated until the list is sorted. Bubble Sort is one of the simplest sorting algorithms, often used for educational purposes to introduce sorting concepts. Its primary use case is for small datasets or as a pedagogical tool.

Algorithm explanation:

Bubble Sort works by repeatedly stepping through the list, comparing each pair of adjacent items and swapping them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, which indicates that the list is sorted. The outer loop runs `n-1` times, and the inner loop performs comparisons and swaps. In the worst-case scenario (a reverse-sorted array), Bubble Sort performs O(n^2) comparisons and O(n^2) swaps. In the best-case scenario (an already sorted array), with the optimization of checking for swaps, it performs O(n) comparisons and O(1) swaps. The space complexity is O(1) because it sorts the array in-place. The algorithm's correctness is based on the fact that each pass guarantees that the largest unsorted element 'bubbles up' to its correct position at the end of the unsorted portion of the array. Edge cases such as an empty array or an array with a single element are handled by an initial check.

Pseudocode:

function bubbleSort(array):
  n = length of array
  if n <= 1:
    return

  repeat:
    swapped = false
    for i from 0 to n-2:
      if array[i] > array[i+1]:
        swap array[i] and array[i+1]
        swapped = true
    n = n - 1 // Optimization: last element is sorted
  until not swapped