diff --git a/scenes/cslib_array.txt b/scenes/cslib_array.txt index 44d96ff..2466a08 100644 --- a/scenes/cslib_array.txt +++ b/scenes/cslib_array.txt @@ -360,6 +360,38 @@ *return +*comment SORT +*comment ------------------------------ +*comment Sorts the elements in a numerical array. +*comment The smallest number will be at the lowest index. +*comment ------------------------------ +*comment params: +*comment p_array_ref(string): the name of the array to sort +*label sort +*params p_array_ref +*set cslib_ret "" +*set p_array_ref &"_" +*temp count {p_array_ref&"count"} +*if count <= 1 + *return +*temp index 2 +*label _sort_loop +*if index > count + *return +*temp left_index index-1 +*if (left_index > 0) + *temp left_value {p_array_ref&left_index} + *temp current_value {p_array_ref&index} + *if (left_value > current_value) + *temp store left_value + *set {p_array_ref&left_index} current_value + *set {p_array_ref&index} store + *set index left_index + *goto _sort_loop +*set index + 1 +*goto _sort_loop + + *comment FOR_EACH *comment ------------------------------ *comment Call a given subroutine against each diff --git a/scenes/test_array.txt b/scenes/test_array.txt index bd4d55c..e2fbd7e 100644 --- a/scenes/test_array.txt +++ b/scenes/test_array.txt @@ -284,6 +284,41 @@ *gosub test_finish 1 test_arr_1 +*comment :::::: SORT tests :::::: +*gosub test_start "sort #1" +*set test_arr_1 99 +*set test_arr_2 2 +*set test_arr_3 77 +*set test_arr_4 4 +*set test_arr_5 5 +*set test_arr_6 9 +*set test_arr_count 6 +*gosub_scene cslib_array sort "test_arr" +*gosub test_assert_equal 2 test_arr_1 +*gosub test_assert_equal 4 test_arr_2 +*gosub test_assert_equal 5 test_arr_3 +*gosub test_assert_equal 9 test_arr_4 +*gosub test_assert_equal 77 test_arr_5 +*gosub test_assert_equal 99 test_arr_6 +*gosub test_finish + +*gosub test_start "sort #2 (two items)" +*set test_arr_1 99 +*set test_arr_2 77 +*set test_arr_count 2 +*gosub_scene cslib_array sort "test_arr" +*gosub test_assert_equal 77 test_arr_1 +*gosub test_assert_equal 99 test_arr_2 +*gosub test_finish + +*gosub test_start "sort #3 (one item)" +*set test_arr_1 99 +*set test_arr_count 1 +*gosub_scene cslib_array sort "test_arr" +*gosub test_assert_equal 99 test_arr_1 +*gosub test_finish + + *comment :::::: TO_STRING tests :::::: *gosub test_start "join #1" *set test_arr_1 1