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

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

Bubble Sort with Optimization

C

Goal -- WPM

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

Bubble Sort with Optimization

Algorithm description:

This C code implements the Bubble Sort algorithm, a simple sorting algorithm that repeatedly steps through the list, compares adjacent elements and swaps them if they are in the wrong order. The algorithm passes through the list until no swaps are needed, which indicates that the list is sorted. This is a fundamental algorithm for learning sorting concepts and is often used as a pedagogical tool.

Algorithm explanation:

Bubble Sort works by repeatedly comparing adjacent elements and swapping them if they are in the wrong order. In each pass, the largest unsorted element 'bubbles up' to its correct position at the end of the unsorted portion. The outer loop controls the number of passes, and the inner loop performs the comparisons and swaps. An optimization is included: if a pass completes without any swaps, the array is already sorted, and the algorithm terminates early. The worst-case and average-case time complexity is O(n^2), while the best-case (already sorted) is O(n) with the optimization. Space complexity is O(1) as it sorts in-place.

Pseudocode:

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