Sorting Algorithms

Rearranging data in the desired order

3-minute read
Made by ChickenFryBytes Studios
Table of Contents

Sorting is used to reorder data in a structure. For example, we may want to reorder the books on a desk by order of the dates they were published, in chronological order. Some common sorting algorithms are:

  • Bubble sort
  • Selection sort
  • Insertion sort
  • Merge sort
  • Quick sort

Sorting is not limited to alphabetical order or chronological order. Some languages designers provide an interface by which we can specify the condition to be used to determine if two elements should be swapped e.g. swap two persons if the first person’s height and the second person’s weight is greater than that of the other person.

Bubble sort

#include <stdbool.h>
#include <stdio.h>

void swap_items(int *item_1, int *item_2) {
  // store value of item 1 into temp variable
  int temp = *item_1;
  // set item 1 value to item 2 value
  *item_1 = *item_2;
  // set item 2 value to temp value
  *item_2 = temp;
}

void show_list(int list[], size_t list_size) {
  for (int i = 0; i < list_size; i++) {
    printf("%d ", list[i]);
  }
  printf("\n");
}

void bubble_sort(int list[], int n) {
  show_list(list, n);

  int i, j;
  bool swapped;
  for (i = 0; i < n - 1; i++) {
    swapped = false;
    for (j = 0; j < n - i - 1; j++) {
      // swap if current item is greater than the next item
      if (list[j] > list[j + 1]) {
        swap_items(&list[j], &list[j + 1]);
        swapped = true;
      }
    }
    if (swapped == false) {
      break;
    }
    show_list(list, n);
  }
}

int main() {
  int list[] = {13, 51, 12, 100, 11, 0, 8, 6, 9, -1, -23};
  // dynamically retrieve size of integer array
  size_t n = sizeof(list) / sizeof(list[0]);

  bubble_sort(list, n);

  return 0;
}
bubble-sort.c
Copy

Selection sort

#include <stdbool.h>
#include <stdio.h>

void swap_items(int *item_1, int *item_2) {
  // store value of item 1 into temp variable
  int temp = *item_1;
  // set item 1 value to item 2 value
  *item_1 = *item_2;
  // set item 2 value to temp value
  *item_2 = temp;
}

void show_list(int list[], size_t list_size) {
  for (int i = 0; i < list_size; i++) {
    printf("%d ", list[i]);
  }
  printf("\n");
}

void selection_sort(int list[], int n) {
  show_list(list, n);

  for (int i = 0; i < n; i++) {
    int min_index = i;
    for (int j = i + 1; j < n; j++) {
      if (list[j] < list[min_index]) {
        min_index = j;
      }
    }
    int temp = list[i];
    list[i] = list[min_index];
    list[min_index] = temp;
    show_list(list, n);
  }
}

int main() {
  int list[] = {13, 51, 12, 100, 11, 0, 8, 6, 9, -1, -23};
  // dynamically retrieve size of integer array
  size_t n = sizeof(list) / sizeof(list[0]);

  selection_sort(list, n);

  return 0;
}
selection-sort.c
Copy

Like our content? Support us via Donations

Resources

Here are some resources we recommend for you to use along with this lesson: