Ascending Order:

function ascendingSort($arr) {
    $length = count($arr);
    for ($i = 0; $i < $length - 1; $i++) {
        for ($j = 0; $j < $length - $i - 1; $j++) {
            if ($arr[$j] > $arr[$j + 1]) {
                $temp = $arr[$j];
                $arr[$j] = $arr[$j + 1];
                $arr[$j + 1] = $temp;
            }
        }
    }
    return $arr;
}

$numbers = array(5, 2, 8, 1, 9);
$sortedNumbers = ascendingSort($numbers);

foreach ($sortedNumbers as $number) {
    echo $number . " ";
}

Descending Order:

function descendingSort($arr) {
    $length = count($arr);
    for ($i = 0; $i < $length - 1; $i++) {
        for ($j = 0; $j < $length - $i - 1; $j++) {
            if ($arr[$j] < $arr[$j + 1]) {
                $temp = $arr[$j];
                $arr[$j] = $arr[$j + 1];
                $arr[$j + 1] = $temp;
            }
        }
    }
    return $arr;
}

$numbers = array(5, 2, 8, 1, 9);
$sortedNumbers = descendingSort($numbers);

foreach ($sortedNumbers as $number) {
    echo $number . " ";
}

Merge Sort – Ascending Order:

function mergeSortAscending($arr) {
    $length = count($arr);
    
    if ($length <= 1) {
        return $arr;
    }
    
    $middle = floor($length / 2);
    $left = array_slice($arr, 0, $middle);
    $right = array_slice($arr, $middle);
    
    $left = mergeSortAscending($left);
    $right = mergeSortAscending($right);
    
    return mergeAscending($left, $right);
}

function mergeAscending($left, $right) {
    $result = array();
    
    while (count($left) > 0 && count($right) > 0) {
        if ($left[0] <= $right[0]) {
            array_push($result, array_shift($left));
        } else {
            array_push($result, array_shift($right));
        }
    }
    
    return array_merge($result, $left, $right);
}

$numbers = array(5, 2, 8, 1, 9);
$sortedNumbersAscending = mergeSortAscending($numbers);

foreach ($sortedNumbersAscending as $number) {
    echo $number . " ";
}

Merge Sort – Descending Order:

function mergeSortDescending($arr) {
    $length = count($arr);
    
    if ($length <= 1) {
        return $arr;
    }
    
    $middle = floor($length / 2);
    $left = array_slice($arr, 0, $middle);
    $right = array_slice($arr, $middle);
    
    $left = mergeSortDescending($left);
    $right = mergeSortDescending($right);
    
    return mergeDescending($left, $right);
}

function mergeDescending($left, $right) {
    $result = array();
    
    while (count($left) > 0 && count($right) > 0) {
        if ($left[0] >= $right[0]) {
            array_push($result, array_shift($left));
        } else {
            array_push($result, array_shift($right));
        }
    }
    
    return array_merge($result, $left, $right);
}

$numbers = array(5, 2, 8, 1, 9);
$sortedNumbersDescending = mergeSortDescending($numbers);

foreach ($sortedNumbersDescending as $number) {
    echo $number . " ";
}

Leave a Reply

Your email address will not be published. Required fields are marked *