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

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

Bubble Sort Implementation

C

Goal -- WPM

Ready
Exercise Algorithm Area
1#include <stdio.h>
2
3// Helper function to swap two integers
4void swap(int* xp, int* yp)
5{
6int temp = *xp;
7*xp = *yp;
8*yp = temp;
9}
10
11// Bubble sort function to sort an array of integers
12void bubbleSort(int arr[], int n)
13{
14int i, j;
15int swapped;
16for (i = 0; i < n - 1; i++)
17{
18swapped = 0;
19// Last i elements are already in place
20for (j = 0; j < n - i - 1; j++)
21{
22if (arr[j] > arr[j + 1])
23{
24swap(&arr[j], &arr[j + 1]);
25swapped = 1;
26}
27}
28
29// If no two elements were swapped by inner loop, then break
30if (swapped == 0)
31break;
32}
33}
34
35// Driver program to test above functions
36int main()
37{
38int arr[] = {64, 34, 25, 12, 22, 11, 90};
39int n = sizeof(arr) / sizeof(arr[0]);
40bubbleSort(arr, n);
41printf("Sorted array: \n");
42for (int i = 0; i < n; i++)
43printf("%d ", arr[i]);
44printf("\n");
45return 0;
46}
Algorithm description viewbox

Bubble Sort Implementation

Algorithm description:

Bubble Sort is a simple sorting algorithm that 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. It is commonly used for educational purposes due to its simplicity.

Algorithm explanation:

Bubble Sort works by repeatedly stepping through the list, comparing adjacent elements and swapping them if they are in the wrong order. The pass through the list is repeated until the list is sorted. The algorithm has a time complexity of O(n^2) in the worst and average cases, and O(n) in the best case (when the array is already sorted). Its space complexity is O(1) as it sorts in-place. An optimization is included to detect if a pass completes with no swaps, indicating the array is sorted and allowing for early termination. The invariant maintained is that after each pass, the largest unsorted element 'bubbles up' to its correct position at the end of the unsorted portion.

Pseudocode:

function bubbleSort(array):
  n = length(array)
  for i from 0 to n-2:
    swapped = false
    for j from 0 to n-i-2:
      if array[j] > array[j+1]:
        swap(array[j], array[j+1])
        swapped = true
    if not swapped:
      break
  return array