JIYIK CN >

Current Location:Home > Learning > ALGORITHM >

Core code of commonly used sorting algorithms

Author:JIYIK Last Updated:2025/03/19 Views:

In the article "Common Sorting Algorithms", we briefly introduced the ideas and implementation steps of various sorting algorithms. In this article, I will share the core codes of these sorting algorithms with you.

The complete code of all sorting algorithms is on github, click here to download .

1. Direct insertion sort

The following is the encapsulated direct insertion sort function

function InsertSort(&$arr){
    for($i=1;$i<count($arr);$i++){
        $p = $arr[$i];
        for($j=$i-1;$j>=0;$j--){
            if($arr[$j]>$p){
                $arr[$j+1] = $arr[$j];
            }else{
                break;
            }
        }
        $arr[$j+1] = $p;
    }
}

2. Binary Insertion Sort

The following is the encapsulated binary insertion sort function

function HalfInsertSort(&$arr){
    for($i=1;$i<count($arr);$i++){
        if($arr[$i]<$arr[$i-1]){
            //Use binary search to find the appropriate position
            $low = 0;
            $high = $i-1;
            $pos = floor(($low+$high)/2);
            $key = $arr[$i];
            while($low<$high){
                if($arr[$pos]>$key){
                    $high = $pos-1;
                }elseif($arr[$pos]<=$key){
                    $low = $pos+1;
                }
                $pos = ceil(($low+$high)/2);
            }
            //End of binary searchif
            ($arr[$pos]>$arr[$i]){
                $pos = $pos-1;
            }
            for($j=$i-1;$j>$pos;$j--){
                $arr[$j+1]=$arr[$j];
            }
            $arr[$j+1] = $key;
        }
    }
}

3. Table insertion sort

The following is the encapsulated table insertion sort function

function TableInsertSort(&$arr,&$link){
    $link[0]=array('next'=>1);//初始化链表  $link第一个元素仅仅作为头部
    $link[1]=array('next'=>0); //将第一个元素放入$link
    /*
     * 开始遍历数组 从第二个元素开始
    */
    for($i=2;$i<=count($arr);$i++){
        $p = $arr[$i]; //存储当前待排序的元素
        $index =0;
        $next = 1;  //从开始位置查找链表
        while($next!=0){
            if($arr[$next]['age']<$p['age']){
                $index = $next;
                $next = $link[$next]['next'];
            }
            else break;
        }
        if($next == 0){
            $link[$i]['next'] = 0;
            $link[$index]['next'] = $i;
        }else{
            $link[$i]['next']=$next;
            $link[$index]['next']=$i;
        }
    }
}

4.希尔排序

下面是封装的希尔排序的函数

function ShellSort(&$arr){
    /*
     * 首先初始化 增量  数组长度/2 取整 floor() 函数向下取整  对于增量每次循环都由 当前增量/2
     */
    for($dl=floor(count($arr)/2);$dl>=1;$dl=floor($dl/2)){
        /*
         * 每次从 增量的位置开始,直到数组递增变量达到数组的长度
         */
        for($j=$dl;$j<count($arr);$j++){
            for($i=$j-$dl;$i>=0;$i-=$dl){
                if($arr[$i+$dl]<$arr[$i]){
                    $temp = $arr[$i+$dl];
                    $arr[$i+$dl]=$arr[$i];
                    $arr[$i]=$temp;
                }
            }
        }
    }
}

5.归并排序

下面是归并排序的递归实现

function MergeSortRecurse(&$arr,$l,$r){
    if($r <= $l) return ;
    $m = floor(($l+$r)/2);
    MergeSort($arr,$l,$m);
    MergeSort($arr,$m+1,$r);
    $arr = Merge($arr,$l,$m,$r);
}

下面是归并排序的非递归方式的实现

function MergeSort(&$arr){
    $stack = array();
    $stack1 = array();
    $temp = array(0,count($arr)-1,floor((0+count($arr)-1)/2));
    array_push($stack,$temp);
    while(count($stack)>0){
        $temp = array_pop($stack);
        array_push($stack1,$temp);
        if($temp[0]<$temp[2]){
            array_push($stack,array($temp[0],$temp[2],floor(($temp[0]+$temp[2])/2)));
        }
        if($temp[2]+1<$temp[1]){
            array_push($stack,array($temp[2]+1,$temp[1],floor(($temp[2]+1+$temp[1])/2)));
        }
    }
    while(count($stack1)>0){
        $temp = array_pop($stack1);
        $arr = Merge($arr,$temp[0], $temp[2], $temp[1]);
    }
}

6. 快速排序

下面是快速排序的递归方式的实现

function FastSortRecurse(&$arr,$s,$e){
    if($s>=$e) return ;
    $nextP = FindPiv($arr,$s,$e);  //找到下一个基准所在位置
    FastSortRecurse($arr,$s,$nextP-1);
    FastSortRecurse($arr,$nextP+1,$e);
}

下面是快速排序的非递归方式的实现

function FastSort(&$arr){
    $stack = array();
    array_push($stack,array(0,count($arr)-1));
    while(count($stack)>0){
        $temp = array_pop($stack);
        $p = FindPiv($arr, $temp[0], $temp[1]);
        if($p+1<$temp[1]) array_push($stack,array($p+1,$temp[1]));
        if($temp[0]<$p-1) array_push($stack,array($temp[0],$p-1));
    }
}

7. 堆排序

下面是封装的堆排序的函数——其实现是大顶堆

function HeapSort(&$arr){
    $start = floor(count($arr)/2); //找到最后一个非叶子节点
    $end = count($arr);
    /*
     * 构造大顶堆
    */
    while($start>0){
        $p = $start;
        while($p){
            $p = MakeHeapChild($arr,$p,$end);
        }
        $start-- ;
    }
    //构造大顶堆结束
    /*
     * 交换顶部节点和最后一个叶子节点 依次调整大顶堆
     */
    while($end>1){
        swap($arr,0,$end-1);
        $end--;
        $p = 1;
        while($p){
            $p = MakeHeapChild($arr,$p,$end);
        }
    }
}

8.选择排序

下面是封装的选择排序的函数

function SelectSort(&$arr){
    $end = count($arr)-1;
    do{
        $p = 0;
        for($i=0;$i<=$end;$i++){
            if($arr[$i]>$arr[$p]){
                $p = $i;
            }
        }
        swap($arr,$p,$end);
    }while(--$end>0);
}

9. 冒泡排序

下面是封装的冒泡排序的实现函数

function BubbleSort(&$arr){
    $end = count($arr)-1;
    while($end>0){
        $flag = false;
        for($i=0;$i<$end;$i++){
            if($arr[$i]>$arr[$i+1]){
                swap($arr,$i,$i+1);
                $flag = true;
            }
        }
        if(!$flag) break;
        $end--;
    }
}

10. 基数排序——LSD

下面是封装的基数排序的LSD方式的函数

function LSD_RadixSort(&$arr){
    //得到序列中最大位数
    $d = FindMaxBit($arr);
    $bucket = array();
    //初始化队列
    for($i=0;$i<10;$i++){
        $bucket[$i]=array('num'=>0,'val'=>array());
    }
    /*
     * 开始进行分配
     */
    $radix = 1;
    for($i=1;$i<=$d;$i++){
        for($j=0;$j<count($arr);$j++){
            $k = floor($arr[$j]/$radix)%10;
            $bucket[$k]['num']++;
            array_push($bucket[$k]['val'],$arr[$j]);
        }
        $arr = array();
        foreach ($bucket as $key => $val) {
            for ($j = 0; $j < $val['num']; $j ++) {
                $arr[] = $val['val'][$j];
            }
        }
        for($l=0;$l<10;$l++){
            $bucket[$l]=array('num'=>0,'val'=>array());
        }
        $radix *= 10;
    }
}

11. 基数排序——MSD

下面是封装的基数排序的MSD方式的函数

function MSD_RadixSort(&$arr,$r){
    $radix = pow(10,$r-1);
    $bucket = array();
    //Initialize queue
    for($i=0;$i<10;$i++){
        $bucket[$i]=array('num'=>0,'val'=>array());
    }
    for($j=0;$j<count($arr);$j++){
        $k = floor($arr[$j]%pow(10,$r)/$radix);
        $bucket[$k]['num']++;
        array_push($bucket[$k]['val'],$arr[$j]);
    }
    for($j=0;$j<10;$j++){
        if($bucket[$j]['num']>1){
            MSD_RadixSort($bucket[$j]['val'],$r-1);
        }
    }
    /*
     * Collect the data in the bucket, now the sequence is ordered
     */
    $arr = array();
    for($j=0;$j<10;$j++){
        for($i=0;$i<count($bucket[$j]['val']);$i++){
            $arr[] = $bucket[$j]['val'][$i];
        }
    }
}

I hope this article is helpful to you.

For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.

Article URL:

Related Articles

Check if a Post exists in PHP

Publish Date:2025/04/13 Views:170 Category:PHP

PHP $_POST is a super global variable that can contain key-value pairs of HTML form data submitted through the post method. We will learn different ways to check $_POST if a and contains some data in this article. These methods will use iss

PHP with Ajax

Publish Date:2025/04/13 Views:139 Category:PHP

We will use PHP and ajax by printing a simple sum of two numbers 2 and . Also, print a php array in JSON. 3 object We will also use PHP with ajax by getting the HTML formatted output from the number division in PHP. Printing simple addition

Store Div Id in PHP variable and pass it to JavaScript

Publish Date:2025/04/13 Views:51 Category:PHP

This article shows you how to div id store a in a PHP variable and pass it to JavaScript code. We will answer the following questions. What is div id ? How to div id store in a PHP variable? How to pass variables to JavaScript code? Let’s

Returns the article tag with ID from the action page

Publish Date:2025/04/13 Views:80 Category:PHP

Let's say you're in a login form and you enter the wrong information; in this case, you probably want to go back to the login page. PHP has a built-in function header() to redirect a page to a specific page. But what if the login page is at

Switching PHP versions on Ubuntu

Publish Date:2025/04/13 Views:78 Category:PHP

Different tasks may require running multiple versions of PHP. You may need to switch PHP versions by running two sites on the same server or testing older versions of code using outdated methods. We can switch PHP versions on Ubuntu using t

Resizing images in PHP

Publish Date:2025/04/13 Views:155 Category:PHP

In this tutorial article, we will discuss about resizing images in PHP. Load the image before resizing Before we can resize an image, we must first load it as an image resource in our script. This is file_get_contents() different from using

PHP upload image

Publish Date:2025/04/13 Views:61 Category:PHP

We can upload images in PHP using simple file upload operation, but first, php.ini file upload should be enabled from Files. This tutorial demonstrates how to upload images in PHP. php.ini Enable file upload from file in PHP to upload image

Creating a signature from Hash_hmac() and Sha256 in PHP

Publish Date:2025/04/13 Views:107 Category:PHP

PHP has one of the best encryption functions for data security. Hash_hmac() The encrypt function is one of the most famous encryptors. We'll show you how to use hash_hmac and sha256 encryptors to create 安全签名 one that you can store i

Updating PHP 7.x to 7.4 on CentOS

Publish Date:2025/04/13 Views:131 Category:PHP

This article shows the steps to update the PHP version from 7.x version to 7.4 in CentOS. How to Update PHP from 7.X to 7.4 in CentOS Update operating system packages. yum update -y Check your PHP version in CentOS. php -v Prints a list of

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial