Snippet. Vala. Sort Array of Integers

This is a nice little function to help you sort an array of integers in Vala.

//======================== START OF FUNCTION ==========================//
// FUNCTION: array_sort_int                                            //
//=====================================================================//
int[] array_sort_int(int[] array){
    bool swapped = true;
    int j = 0;
    int tmp;

    while (swapped) {
        swapped = false;
        j++;
        for (int i = 0; i < array.length - j; i++) {
            if (array[i] > array[i + 1]) {
                tmp = array[i];
                array[i] = array[i + 1];
                array[i + 1] = tmp;
                swapped = true;
             }
        }
    }
    return array;
}
//=====================================================================//
// FUNCTION: array_sort_int                                            //
//========================= END OF FUNCTION ===========================//

Here is an example of its usage.

int[] array_int = {5,2,1,4,5,3,7,9,8};
array_int = array_sort_int(array_int);

Result:


Updated on: 21 Nov 2024