Snippet. Vala. Sort Array of Strings

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

//======================== START OF FUNCTION ==========================//
// FUNCTION: array_sort_string                                         //
//=====================================================================//
string[] array_sort_string(string[] array){
    bool swapped = true;
    int j = 0;
    string 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_string                                         //
//========================= END OF FUNCTION ===========================//

Here is an example of its usage.

string[] array_string = {"Tom","Anna","Cecil","Betty","Dominique","Valeria","Peter","John","Monique"};
array_string = array_sort_string(array_string);

Result:


Updated on: 21 Dec 2024