#include <stdio.h>

/*
******************************************************
Pre-sessional learning for iBSc students
Programming and electronics, Section 5, Extension task
******************************************************

Note:
    Although this script is prepared in C, the code defined in the main() function
    should be compatible with the Arduino-specific language (which is a variant of C).
    To execute, you need to carefully integrate the code defined in main() to your
    Arduino IDE.

Version history:
    Date            Programmer      Description
    ----------      ----------      ----------------------------
    23/08/2024      B LI            create
*/

void bubble_sort(int *array_to_sort, int size);

int main(){

    int array_to_sort[] =  {6, 5, 4, 7, 3, 0, 2, 8, 9, 1, -1};

    // length of the array
    int size = sizeof(array_to_sort)/sizeof(array_to_sort[0]);
    printf("The length of the array is %d \n", size);

    // display the array pending to be sorted
    for (int i = 0; i < size; i++) {
        printf("Element at index %d: %d\n", i, array_to_sort[i]);
    }
    printf("\n");

    // revoke the bubble sort function
    bubble_sort(array_to_sort, size);

    // display the result after sorting
     for (int i = 0; i < size; i++) {
        printf("Element after sort at index %d: %d\n", i, array_to_sort[i]);
    }

    return 0;
}


void bubble_sort(int *array_to_sort, int size){

    int temp;

    // outer loop for size-1 times to check the array
    for (int i = 0; i < size-1; i++) {

        // inner loop for comparison of two adjacent numbers in one check
        for (int j = 0; j < size-i-1; j++){

            if (array_to_sort[j] > array_to_sort[j+1]){

                // this is just the swipe ex. we demonstrated in section 2.
                temp = array_to_sort[j];
                array_to_sort[j] = array_to_sort[j+1];
                array_to_sort[j+1] = temp;

            }
        }

    }


    return 0;

}

