aboutsummaryrefslogtreecommitdiff
path: root/src/sort.c
blob: 6ea4b262ef0f58d1a873ebab0aa29362f1757ffd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include "utils.h"
#include <stdio.h>
void bubblesort(int a[], int n) {
  int comparisons = 0;
  for (int i = 0; i < n; i++) {
    for (int j = 1; j < n - i; j++) {
      comparisons++;
      if (a[j - 1] > a[j]) {
        swap(a, j, j - 1);
      }
    }
    printarr(a, n);
    printf("\n");
  }
}

void selectionsort(int a[], int n) {
  for (int i = 0; i < n; i++) {
    int small = i;
    for (int j = i; j < n; j++) {
      if (a[j] < a[small]) {
        small = j;
      }
    }
    swap(a, i, small);
    printarr(a, n);
    printf("\n");
  }
}

void insertionsort(int a[], int n) {
  for (int i = 1; i < n; i++) {
    int j = i;
    while (j > 0 && a[j - 1] > a[j]) {
      swap(a, j, j - 1);
      j--;
    }
    printarr(a, n);
    printf("\n");
  }
}