/* CS107
 * Lecture Example: Generics
 *
 * This file shows how to implement a
 * bubble sort function for ints that sorts
 * in ascending order.
 */
#include <error.h>
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

/* This function swaps the values of two integers
 * pointed to by p and q. */
void swap_int(int *p, int *q) {
    int tmp = *p;
    *p = *q;
    *q = tmp;
}

void bubble_sort_int(int *arr, size_t n) {
    while (true) {
        bool swapped = false;
        
        for (size_t i = 1; i < n; i++) {
            if (arr[i - 1] > arr[i]) {
                swapped = true;
                int tmp = arr[i - 1];
                arr[i - 1] = arr[i];
                arr[i] = tmp;
            }
        }
        
        if (!swapped) {
            return;
        }
    }
}

int main(int argc, char *argv[]) {
    int nums[] = {4, 2, 12, -5, 56, 14};
    int nums_count = sizeof(nums) / sizeof(nums[0]);
    bubble_sort_int(nums, nums_count);
    
    for (int i = 0; i < nums_count; i++) {
        printf("%d  ", nums[i]);
    }
    printf("\n");
    
    return 0;
}
