0

I've tried to do some sorting with GLib's GenericArray, Slist, List. Sorting with sort_with_data works as expected, but when I've tried Glib's Array it doesn't work, or rather it does something different!

This is my sort function for integers:

[indent=4]

init
    var a = new Array of int
    for i in new array of int = {3, 2, 1, 5, 7}
        a.append_val (i)

    a.sort_with_data (my_func)
    for var i = 0 to (a.length - 1)
        stdout.printf ("%d, ", a.index (i))
    // 3, 2, 1, 5, 7, 
    stdout.putc ('\n')

    a.sort (my_func)
    for var i = 0 to (a.length - 1)
        stdout.printf ("%d, ", a.index (i))
    // 3, 2, 1, 5, 7, 

def my_func (a: int, b: int): int
    return a - b

the output is 3, 2, 1, 5, 7,

I don't know what's wrong. Please don't tell me to use Gee! my question is sort Array of int Thanks!

Naam Famas
  • 124
  • 7
  • possible duplicate of [\[genie/vala\]: How to Sort using a custom comparator?](http://stackoverflow.com/questions/26572319/genie-vala-how-to-sort-using-a-custom-comparator) – Jens Mühlenhoff Oct 29 '14 at 11:36
  • 3
    You have now basically asked the same question *three* times. You should go back to the first question and edit it to show your progress or to add more details. Asking the same thing multiple times is not the way to go. – Jens Mühlenhoff Oct 29 '14 at 11:38

2 Answers2

1

a.length - b.length will sort the strings by length not contents. If you want contents, use a.collate(b).

apmasell
  • 7,033
  • 19
  • 28
0

sort function for GenericArray is more easy to write. but Array's sort function is different.

an example for sort int data, and sort string data

[indent=4]

init
    var a = new Array of int
    var b = new array of int = {3, 8, 6, 5, 7, 4, 1, 2}
    a.append_vals (b, b.length)

    // sort_with_data
    a.sort_with_data ((CompareDataFunc) int_sort)
    stdout.puts ("sort_with_data:\n")

    for var i = 0 to (a.length - 1)
        stdout.printf ("%d, ", a.index (i))
    stdout.putc ('\n')

    // sort
    a.sort ((CompareFunc) int_sort)
    stdout.puts ("sort:\n")

    for var i = 0 to (a.length - 1)
        stdout.printf ("%d, ", a.index (i))

    stdout.puts ("\nsort string:\n")
    // sort string
    var S = new array of string = {
        "zee", "app", "april", "bana", "grap", "oliv", "lim", "apri"
    }

    var T = new Array of string
    T.append_vals (S, S.length)

    T.sort ((CompareFunc) str_sort)

    for var i = 0 to (T.length - 1)
        stdout.printf ("%s, ", T.index (i))

    // app, apri, bana, grap, lim, oliv, zee, 

def int_sort (a: int*, b: int*): int
    return *a - *b

def str_sort (a: char**, b: char**): int
    return strcmp ((string)(*a), (string)(*b))


/* ouput

sort_with_data:
1, 2, 3, 4, 5, 6, 7, 8, 
sort:
1, 2, 3, 4, 5, 6, 7, 8, 
sort string:
app, apri, april, bana, grap, lim, oliv, zee, 

*/
Naam Famas
  • 124
  • 7