Bubble Sort in C

Level 5305 keystrokes

Defines a bubble sort that repeatedly compares neighbouring elements and swaps them when they are in the wrong order, so the largest value bubbles to the end on each pass. It sorts {5, 2, 8, 1, 9} and prints 1 2 5 8 9.

C code

// Sorts the n elements of arr in ascending order
1void bubbleSort(int arr[], int n) {
// n - 1 passes are enough; after pass i, the last i + 1 elements are in place
2 for (int i = 0; i < n - 1; i++) {
// Compares each neighbouring pair in the part that is not yet sorted
3 for (int j = 0; j < n - i - 1; j++) {
// The pair is in the wrong order when the left value is larger
4 if (arr[j] > arr[j + 1]) {
// Swaps the two values using a temporary variable
5 int temp = arr[j];
6 arr[j] = arr[j + 1];
7 arr[j + 1] = temp;
8 }
9 }
10 }
11}
12
// Unsorted input data
13int nums[] = {5, 2, 8, 1, 9};
// Sorts the 5 elements in place, since the array is passed by address
14bubbleSort(nums, 5);
// Prints 1 2 5 8 9, each value followed by a space
15for (int i = 0; i < 5; i++) printf("%d ", nums[i]);

Output

1 2 5 8 9
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this C code and how often they appear.

  • ;× 12
  • [× 9
  • ]× 9
  • +× 9
  • ,× 7
  • (× 7
  • )× 7
  • =× 7
  • {× 5
  • }× 5

More C examples at level 5

← C typing practice