#!/bin/sh
#:
#: Measure the performance of implemented array sort methods.
#:

set -u

export PERFDIR="$(dirname "$0")"
export TESTDIR="${PERFDIR}/.."
. "${TESTDIR}/testsetup.sh"
_p_datadir="${TESTDIR}/../share/local-bsdtools"
. "${_p_datadir}/farray.sh"
. "${_p_datadir}/farray-ext.sh"


fatal() {
    exit 1 "ERROR: $@" 1>&2
}


get_ts() {
    /usr/bin/ntpq -c "rv 0 clock" localhost
}


#:
#: Run all tests with the same random array
#:
#: Args:
#:   $1 (int): The length of the randon array to use to
#:
test_for() {
    # $1

    local UNSORTED TEST

    echo "Testing for an array with length ${1}"

    create_random_array UNSORTED "${1}"

    if [ "${1}" -le 2000 ]; then
	farray_create TEST
	farray_splice "" TEST 1 "" UNSORTED
	echo "===> Gnome Sort with ${1} items"
	get_ts
	farray_gnomesort TEST
	get_ts
	check_array_is_sorted "$TEST" || fatal "sort failed"
	farray_release TEST
    else
	echo "===> SKIPPED: Gnome Sort with ${1} items"
    fi


    if [ "${1}" -le 2000 ]; then
	farray_create TEST
	farray_splice "" TEST 1 "" UNSORTED
	echo "===> Insertion Sort with ${1} items"
	get_ts
	farray_insertionsort TEST
	get_ts
	check_array_is_sorted "$TEST" || fatal "sort failed"
	farray_release TEST
    else
	echo "===> SKIPPED: Insertion Sort with ${1} items"
    fi    

    if [ "${1}" -le 50000 ]; then
	farray_create TEST
	farray_splice "" TEST 1 "" UNSORTED
	echo "===> Shell Sort with ${1} items"
	get_ts
	farray_shellsort TEST
	get_ts
	check_array_is_sorted "$TEST" || fatal "sort failed"
	farray_release TEST
    else
	echo "===> SKIPPED: Shell Sort with ${1} items"
    fi

    farray_create TEST
    farray_splice "" TEST 1 "" UNSORTED
    echo "===> Heap Sort (standard) with ${1} items"
    get_ts
    farray_heapsort TEST
    get_ts
    check_array_is_sorted "$TEST" || fatal "sort failed"
    farray_release TEST

    farray_create TEST
    farray_splice "" TEST 1 "" UNSORTED
    echo "===> Heap Sort (bottom-up) with ${1} items"
    get_ts
    farray_heapsort_bottomup TEST
    get_ts
    check_array_is_sorted "$TEST" || fatal "sort failed"
    farray_release TEST    

    farray_release UNSORTED
}


test_for 2
test_for 3
test_for 4
test_for 5
test_for 10
test_for 20
test_for 50
test_for 100
test_for 500
test_for 1000
test_for 2000
test_for 5000
test_for 10000
test_for 20000
test_for 50000
