changeset 773:bae0652d0577

farray.sh: More tests for sorting: using a random array
author Franz Glasner <fzglas.hg@dom66.de>
date Wed, 23 Oct 2024 18:33:38 +0200
parents e942b091b762
children 75a8b69c04f0
files tests/farray-array.t tests/testsetup.sh
diffstat 2 files changed, 65 insertions(+), 0 deletions(-) [+]
line wrap: on
line diff
--- a/tests/farray-array.t	Wed Oct 23 16:44:12 2024 +0200
+++ b/tests/farray-array.t	Wed Oct 23 18:33:38 2024 +0200
@@ -1385,6 +1385,7 @@
 
   $ farray_create TEST 5 3 2 4
   $ farray_sort TEST
+  $ check_array_is_sorted "$TEST"
   $ farray_debug TEST
   DEBUG: array `TEST' has length 4
   DEBUG:   the items:
@@ -1395,6 +1396,19 @@
   $ farray_release TEST
   $ check_no_array_artifacts
 
+  $ create_random_array UNSORTED 1000
+  $ check_array_is_sorted "$UNSORTED"
+  [1]
+
+  $ farray_create TEST
+  $ farray_splice "" TEST 1 "" UNSORTED
+  $ farray_gnomesort TEST
+  $ check_array_is_sorted "$TEST"
+  $ farray_release TEST
+
+  $ farray_release UNSORTED
+  $ check_no_array_artifacts
+
 
 Binary Search
 =============
--- a/tests/testsetup.sh	Wed Oct 23 16:44:12 2024 +0200
+++ b/tests/testsetup.sh	Wed Oct 23 18:33:38 2024 +0200
@@ -57,3 +57,54 @@
 	return 0
     fi
 }
+
+
+#:
+#: Create an new array with random entries.
+#:
+#: Args:
+#:   $1 (str): The variable name of the array where to store the 
+#:   $2 (int): The number of array entries
+#:
+#: Input (Globals):
+#: 
+create_random_array() {
+    # $1 $2
+
+    local _arr _n
+
+    farray_create _arr
+    for _n in $(/usr/bin/jot -r "${2}"  100000000 999999999); do
+	farray_append _arr "${_n}"
+    done
+    setvar "${1}" "${_arr}"
+}
+
+
+#:
+#: Check that an array is sorted
+#:
+#: Args:
+#:   $1 (str): The array
+#:
+#: Returns:
+#:   int: 0 (truthy) if the array `$1` is sorted, 1 otherwise
+#:
+check_array_is_sorted() {
+    # $1
+
+    local i len prev_item cur_item
+
+    farray_length len "$1"
+
+    [ "${len}" -le 1 ] && return 0
+    farray_get prev_item "$1" 1
+    i=2
+    while [ "${i}" -le "${len}" ]; do
+	farray_get cur_item "$1" "${i}"
+	[ "${prev_item}" '>' "${cur_item}" ] && return 1
+	prev_item="${cur_item}"
+	i=$((i + 1))
+    done
+    return 0
+}