Fundamentals 15 min read

Master PHP Sorting Algorithms: Insertion, Selection, Bubble, Quick, Shell & More

This comprehensive guide walks through classic PHP sorting techniques—including insertion, selection, bubble, quick, and shell sorts—along with essential string utilities such as length calculation, reversal, comparison, substring search, replacement, insertion, deletion, copying, concatenation, simple encoding/decoding, and basic encryption/decryption, providing clear explanations and ready‑to‑run code examples for each algorithm.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
Master PHP Sorting Algorithms: Insertion, Selection, Bubble, Quick, Shell & More

1. Insertion Sort (One‑Dimensional Array)

The insertion sort builds a sorted portion of the array by repeatedly taking the next element and inserting it into its correct position among the already sorted elements.

<?php
function insert_sort($arr){
    $count = count($arr);
    for($i = 1; $i < $count; $i++){
        $tmp = $arr[$i];
        for($j = $i - 1; $j >= 0 && $arr[$j] > $tmp; $j--){
            $arr[$j + 1] = $arr[$j];
        }
        $arr[$j + 1] = $tmp;
    }
    return $arr;
}
?>

2. Selection Sort (One‑Dimensional Array)

Selection sort repeatedly finds the minimum (or maximum) element from the unsorted portion and swaps it with the first unsorted element, expanding the sorted region.

<?php
function select_sort($arr){
    $count = count($arr);
    for($i = 0; $i < $count; $i++){
        $minIdx = $i;
        for($j = $i + 1; $j < $count; $j++){
            if($arr[$j] < $arr[$minIdx]){
                $minIdx = $j;
            }
        }
        if($minIdx != $i){
            $tmp = $arr[$i];
            $arr[$i] = $arr[$minIdx];
            $arr[$minIdx] = $tmp;
        }
    }
    return $arr;
}
?>

3. Bubble Sort (One‑Dimensional Array)

Bubble sort repeatedly steps through the list, compares adjacent elements and swaps them if they are in the wrong order, bubbling the largest unsorted value to its final position each pass.

<?php
function bubble_sort($array){
    $count = count($array);
    if($count <= 1) return $array;
    for($i = 0; $i < $count; $i++){
        for($j = $count - 1; $j > $i; $j--){
            if($array[$j] < $array[$j - 1]){
                $tmp = $array[$j];
                $array[$j] = $array[$j - 1];
                $array[$j - 1] = $tmp;
            }
        }
    }
    return $array;
}
?>

4. Quick Sort (One‑Dimensional Array)

Quick sort selects a pivot element, partitions the array into elements less than or equal to the pivot and those greater, then recursively sorts the partitions.

<?php
function quickSort(&$arr){
    if(count($arr) <= 1) return $arr;
    $pivot = $arr[0];
    $left = $right = [];
    for($i = 1; $i < count($arr); $i++){
        if($arr[$i] <= $pivot) $left[] = $arr[$i];
        else $right[] = $arr[$i];
    }
    return array_merge(quickSort($left), [$pivot], quickSort($right));
}
?>

5. Shell Sort

Shell sort improves insertion sort by allowing exchanges of far‑apart elements. The gap is repeatedly halved until it becomes 1.

<?php
function shell_sort(&$arr){
    $n = count($arr);
    for($gap = floor($n/2); $gap > 0; $gap = floor($gap/2)){
        for($i = $gap; $i < $n; $i++){
            $temp = $arr[$i];
            for($j = $i; $j >= $gap && $arr[$j-$gap] > $temp; $j -= $gap){
                $arr[$j] = $arr[$j-$gap];
            }
            $arr[$j] = $temp;
        }
    }
    return $arr;
}
?>

6. Binary Search

Binary search recursively halves a sorted array to locate a target value, returning true when found.

<?php
function bin_search($array, $min_key, $max_key, $value){
    if($min_key <= $max_key){
        $key = intval(($min_key + $max_key) / 2);
        if($array[$key] == $value) return true;
        elseif($value < $array[$key])
            return bin_search($array, $min_key, $key - 1, $value);
        else
            return bin_search($array, $key + 1, $max_key, $value);
    }
    return false;
}
?>

7. Delete Element from Linear List (Array Implementation)

Removes the element at index $i by shifting subsequent elements left and truncating the array.

<?php
function delete_array_element($array, $i){
    $len = count($array);
    for($j = $i; $j < $len - 1; $j++){
        $array[$j] = $array[$j + 1];
    }
    array_pop($array);
    return $array;
}
?>

8. String Length

Calculates the length of a string without using built‑in strlen.

<?php
function my_strlen($str){
    if($str === '') return 0;
    $count = 0;
    while(true){
        if(isset($str[$count])){ $count++; continue; }
        else break;
    }
    return $count;
}
?>

9. String Reverse

Reverses a string by iterating from the end to the start.

<?php
function strrev_custom($str){
    if($str === '') return '';
    $rev = '';
    for($i = my_strlen($str) - 1; $i >= 0; $i--){
        $rev .= $str[$i];
    }
    return $rev;
}
?>

10. String Comparison

Compares two strings lexicographically, returning -1, 0, or 1.

<?php
function strcmp_custom($s1, $s2){
    $len1 = my_strlen($s1);
    $len2 = my_strlen($s2);
    $min = $len1 < $len2 ? $len1 : $len2;
    for($i = 0; $i < $min; $i++){
        if($s1[$i] != $s2[$i]) return $s1[$i] < $s2[$i] ? -1 : 1;
    }
    if($len1 < $len2) return -1;
    if($len1 > $len2) return 1;
    return 0;
}
?>

11. Substring Search (strstr)

Finds the first occurrence of $substr in $str and returns its position.

<?php
function strstr_custom($str, $substr){
    $m = my_strlen($str);
    $n = my_strlen($substr);
    if($m < $n) return false;
    for($i = 0; $i <= $m - $n; $i++){
        $sub = substr($str, $i, $n);
        if(strcmp_custom($sub, $substr) == 0) return $i;
    }
    return false;
}
?>

12. String Replace

Replaces all occurrences of $substr with $newsubstr in $str.

<?php
function str_replace_custom($substr, $newsubstr, $str){
    $m = my_strlen($str);
    $n = my_strlen($substr);
    if(strpos($str, $substr) === false) return $str;
    $result = '';
    $i = 0;
    while($i <= $m - $n){
        if(substr($str, $i, $n) === $substr){
            $result .= $newsubstr;
            $i += $n;
        } else {
            $result .= $str[$i];
            $i++;
        }
    }
    $result .= substr($str, $i);
    return $result;
}
?>

13. Insert Substring

Inserts $substr at position $i inside $str.

<?php
function str_insert($str, $i, $substr){
    $start = '';
    for($j = 0; $j < $i; $j++) $start .= $str[$j];
    $end = '';
    for($j = $i; $j < my_strlen($str); $j++) $end .= $str[$j];
    return $start . $substr . $end;
}
?>

14. Delete Substring

Deletes $j characters starting from index $i in $str.

<?php
function str_delete($str, $i, $j){
    $head = '';
    for($c = 0; $c < $i; $c++) $head .= $str[$c];
    $tail = '';
    for($c = $i + $j; $c < my_strlen($str); $c++) $tail .= $str[$c];
    return $head . $tail;
}
?>

15. String Copy

Copies the contents of $s1 into $s2.

<?php
function strcpy_custom($s1, $s2){
    if(my_strlen($s1) == 0 || !isset($s2)) return;
    for($i = 0; $i < my_strlen($s1); $i++){
        $s2[$i] = $s1[$i];
    }
    return $s2;
}
?>

16. String Concatenation

Concatenates $s2 onto the end of $s1.

<?php
function strcat_custom($s1, $s2){
    if(!isset($s1) || !isset($s2)) return;
    $new = $s1;
    for($i = 0; $i < count($s2); $i++){
        $new .= $s2[$i];
    }
    return $new;
}
?>

17. Simple Encode (php_encode)

Encodes a string by shifting character codes; characters in the range 32‑106 are increased by 20, and those in 107‑126 are decreased by 75.

<?php
function php_encode($str){
    if($str === '' && my_strlen($str) > 128) return false;
    $s = '';
    for($i = 0; $i < my_strlen($str); $i++){
        $c = ord($str[$i]);
        if($c > 31 && $c < 107) $c += 20;
        elseif($c > 106 && $c < 127) $c -= 75;
        $s .= chr($c);
    }
    return $s;
}
?>

18. Simple Decode (php_decode)

Reverses the encoding performed by php_encode by applying the opposite shifts.

<?php
function php_decode($str){
    if($str === '' && my_strlen($str) > 128) return false;
    $s = '';
    for($i = 0; $i < my_strlen($str); $i++){
        $c = ord($str[$i]);
        if($c > 106 && $c < 127) $c += 20;
        elseif($c > 31 && $c < 107) $c -= 75;
        $s .= chr($c);
    }
    return $s;
}
?>

19. Simple Encryption (php_encrypt)

Encrypts a string by mapping each character through a predefined substitution table.

<?php
function php_encrypt($str){
    $encrypt_key = 'abcdefghijklmnopqrstuvwxyz1234567890';
    $decrypt_key = 'ngzqtcobmuhelkpdawxfyivrsj2468021359';
    if(my_strlen($str) == 0) return false;
    $enstr = '';
    for($i = 0; $i < my_strlen($str); $i++){
        for($j = 0; $j < my_strlen($encrypt_key); $j++){
            if($str[$i] == $encrypt_key[$j]){
                $enstr .= $decrypt_key[$j];
                break;
            }
        }
    }
    return $enstr;
}
?>

20. Simple Decryption (php_decrypt)

Reverses the substitution performed by php_encrypt using the inverse table.

<?php
function php_decrypt($str){
    $encrypt_key = 'abcdefghijklmnopqrstuvwxyz1234567890';
    $decrypt_key = 'ngzqtcobmuhelkpdawxfyivrsj2468021359';
    if(my_strlen($str) == 0) return false;
    $decrypted = '';
    for($i = 0; $i < my_strlen($str); $i++){
        for($j = 0; $j < my_strlen($decrypt_key); $j++){
            if($str[$i] == $decrypt_key[$j]){
                $decrypted .= $encrypt_key[$j];
                break;
            }
        }
    }
    return $decrypted;
}
?>

All the functions above are written in pure PHP without reliance on built‑in shortcuts, making them ideal for learning fundamental algorithmic thinking, data‑structure manipulation, and basic cryptographic transformations.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PHPData StructuresAlgorithmsencryptionString FunctionsSorting
Laravel Tech Community
Written by

Laravel Tech Community

Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.