PHP实现基本算法代码

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了PHP实现基本算法代码相关的知识,希望对你有一定的参考价值。

<?

//--------------------

// 基本数据结构算法

//--------------------

//二分查找,要求数组已经排好序,首先,假设表中元素是按升序排列,将表中间位置记录的关键字与查找关键字比较,如果两者相等,则查找成功;否则利用中间位置记录将表分成前、后两个子表,如果中间位置记录的关键字大于查找关键字,则进一步查找前一子表,否则进一步查找后一子表。重复以上过程,直到找到满足条件的记录,使查找成功,或直到子表不存在为止,此时查找不成功。

//$arr array数组 $low int 数组起始元素下标 $high int 数组末尾元素下标

//$k 要查找的元素 mixed 成功返回数组下标 失败返回-1

 function bin_sch($array,$low,$high,$k){

        if($low <= $high){

        $mid = intval(($low+$high)/2);

        if($array[$mid] == $k){

                return $mid;

        }elseif($k < $array[$mid]){

                return bin_sch($array,$low,$mid-1,$k);

        }else{

                return bin_sch($array,$mid+1,$high,$k);

        }

        }

        return -1;

 }

//选择排序:首先在未排序序列中找到最小(大)元素,存放到排序序列的起始位置,然后再从剩余未排序元素中继续寻找最小(大)元素,然后放到已排序序列的末尾。以此类推,直到所有元素均排序完毕。

function selectSort($array)

{

    $count = count( $array );

    if( $count <= 1 ) return $array;

    for($i = 0; $i < $count-1; $i ++)

    {

        $min = $i;

        for( $j = $i+1; $j < $count; $j ++)

        {

            if( $array[$min] > $array[$j] )

            {

                $min = $j;

            }

        }

        if( $min != $i )

        {

            $temp = $array[$min];

            $array[$min] = $array[$i];

            $array[$i] = $temp;

        }

    }   

    return $array;

}

//快速排序:1.从数列中挑出一个元素,称为"基准"。2. 重新排序数列,所有元素比基准值小的摆放在基准前面,所有元素比基准值大的摆在基准的后面(相同的数可以到任一边)。在这个分区结束之后,该基准就处于数列的中间位置。这个称为分区操作。3. 递归地把小于基准值元素的子数列和大于基准值元素的子数列排序。

function quickSort($array){

$count  = count($array);

if($count <= 1)

return $array;

$left = $right = array();

$mid_value = $array[0];

for($i = 1;$i < $count;$i++){

if($array[$i] < $mid_value){

$left[] = $array[$i];

}else{

$right[] = $array[$i];

}

}

return array_merge(quickSort($left),(array)$mid_value,quickSort($right));

}

$arr = [2,45,6,34,12,7,76,89,44,23,66,22,55];

$arr = quickSort($arr);

print_r($arr);

请使用php设计一个函数,对学生英语考试得分从高到低排序,输入时所有学生的学号和考试得分,返回排好序的考试得分和对应学生的学号。考试满分为100,得分可能会有小数,由于考试评分要求,小数位只会是0或0.5

function quick_sort(&$arr,$left,$right){

    if($left < $right){

        

        //依次取出数组的然后跟后面对比排序

        $privot = $arr[$left];

        $low = $left;

        $high = $right;

        while($low < $high){

 

            //同后面的作比较要是小于第一个则调换到前面

            while($low < $high && $arr[$high][‘score‘] >= $privot[‘score‘]){

                $high--;

            }

            $tmp = $arr[$low];

            $arr[$low] = $arr[$high];

            $arr[$high] = $tmp;

 

            //同前面的作比较若是大于后面的则调换到后面去

            while($low < $high && $arr[$low][‘score‘] <= $privot[‘score‘]){

                $low++;

            }

            $tmp = $arr[$low];

            $arr[$low] = $arr[$high];

            $arr[$high] = $tmp;

            //以low为中间值再去回调再去排序

            quick_sort($arr,$left,$low-1);

            quick_sort($arr,$low+1,$right);

        }

    }

}

$english = array(

            array(‘sid‘=>1,‘score‘=>76),

            array(‘sid‘=>2,‘score‘=>93),

            array(‘sid‘=>3,‘score‘=>68.5),

            array(‘sid‘=>4,‘score‘=>82.5),

        );

$left = 0;

$right = count($english) - 1;

quick_sort($english,$left,$right);

echo "<pre>";

print_r($english);

echo "</pre>";

//插入排序是一种简单直观的排序算法。它的工作原理是通过构建有序序列,对于未排序数据,在已排序序列中从后向前扫描,找到相应位置插入。插入排序在实现上,通常采用in-place排序(即只需要用到O(1)的额外空间的排序),因而在从后向前扫描过程中,需要反复把已排序元素逐步向后挪位,为最新元素提供插入空间。

function insertSort($array)

{

    $count = count( $array );

    if( $count <= 1 ) return $array;

 

    for($i = 1; $i < $count; $i ++)

    {

        $temp = $array[$i];

        for($j = $i-1; $j >= 0 && $array[$j] > $temp; $j --)

        {

            $array[$j+1] = $array[$j];

        }

        $array[$j+1] = $temp;

    }

 

return $array;

}

//顺序查找(数组里查找某个元素): 

function seq_sch($arr,$k){

        for($i = 0,$n = count($arr);$i < $n;$i++){

                if($arr[$i] == $k){

                        break;

                }

        }

        if($i < $n ){

                return $i;

        }else{

                return -1;

        }

 }

//冒泡排序(数组排序):它重复地走访过要排序的数列,一次比较两个元素,如果它们的顺序错误就把它们交换过来。 

function bubble_sort($array)

{

        $count = count($array);

        if ($count <= 1) return false;

 

        for($i=0; $i<$count; $i++){

                for($j=1; $j<$count-$i; $j++){

                        if ($array[$j-1] < $array[$j]){

                                $tmp = $array[$j-1];

                                $array[$j-1] = $array[$j];

                                $array[$j] = $tmp;

                        }

                }

        }

        return $array;

}

//线性表的删除(数组中实现) 

function delete_array_element($array, $i)

{

        $len = count($array);  

        for ($j=$i; $j<$len; $j++){

                $array[$j] = $array[$j+1];

        }

        array_pop($array);

        return $array;

//------------------------

// PHP内置字符串函数实现

//------------------------ 

//字符串长度

function strlen($str)

{

        if ($str == ‘‘) return 0;

 

        $count = 0;

        while (1){

                if ($str[$count] != NULL){

                        $count++;

                        continue;

                }else{

                        break;

                }

        }

        return $count;

}

//截取子串

function substr($str, $start, $length=NULL)

{

        if ($str==‘‘ || $start>strlen($str)) return;

        if (($length!=NULL) && ($start>0) && ($length>strlen($str)-$start)) return;

        if (($length!=NULL) && ($start<0) && ($length>strlen($str)+$start)) return;

        if ($length == NULL) $length = (strlen($str) - $start);

         

        if ($start < 0){

                for ($i=(strlen($str)+$start); $i<(strlen($str)+$start+$length); $i++) {

                        $substr .= $str[$i];

                }

        }

 

        if ($length > 0){

                for ($i=$start; $i<($start+$length); $i++) {

                        $substr .= $str[$i];

                }

        }

 

        if ($length < 0){

                for ($i=$start; $i<(strlen($str)+$length); $i++) {

                        $substr .= $str[$i];

                }

        }

        return $substr;

}

//字符串翻转

function strrev($str)

{

        if ($str == ‘‘) return 0;

        for ($i=(strlen($str)-1); $i>=0; $i--){

                $rev_str .= $str[$i];

        }

        return $rev_str;

}

//字符串比较 

function strcmp($s1, $s2)

{

        if (strlen($s1) < strlen($s2)) return -1;

        if (strlen($s1) > strlen($s2)) return 1;

 

        for ($i=0; $i<strlen($s1); $i++){

                if ($s1[$i] == $s2[$i]){

                        continue;

                }else{

                        return false;

                }

        }

        return 0;

}

//查找字符串

function strstr($str, $substr)

{

        $m = strlen($str);

        $n = strlen($substr);

        if ($m < $n) return false;

 

        for ($i=0; $i<=($m-$n+1); $i++){

                $sub = substr($str, $i, $n);

                if (strcmp($sub, $substr) == 0)  return $i;

        }

        return false;

}

//字符串替换

function str_replace($substr, $newsubstr, $str)

{

        $m = strlen($str);

        $n = strlen($substr);

        $x = strlen($newsubstr);

        if (strchr($str, $substr) == false) return false;

 

        for ($i=0; $i<=($m-$n+1); $i++){

                $i = strchr($str, $substr);

                $str = str_delete($str, $i, $n);

                $str = str_insert($str, $i, $newstr);

        }

        return $str;

}

//--------------------

// 自实现字符串处理函数

//--------------------

//插入一段字符串

function str_insert($str, $i, $substr)

{

        for($j=0; $j<$i; $j++){

                $startstr .= $str[$j];

        }

        for ($j=$i; $j<strlen($str); $j++){

                $laststr .= $str[$j];

        }

        $str = ($startstr . $substr . $laststr);

 

        return $str;

}

//删除一段字符串

function str_delete($str, $i, $j)

{

        for ($c=0; $c<$i; $c++){

                $startstr .= $str[$c];

        }

        for ($c=($i+$j); $c<strlen($str); $c++){

                $laststr .= $str[$c];

        }

        $str = ($startstr . $laststr);

 

        return $str;

}

//复制字符串

function strcpy($s1, $s2)

{

        if (strlen($s1)==NULL || !isset($s2)) return;

 

        for ($i=0; $i<strlen($s1); $i++){

                $s2[] = $s1[$i];

        }

        return $s2;

}

//连接字符串

function strcat($s1, $s2)

{

        if (!isset($s1) || !isset($s2)) return;

        $newstr = $s1;

        for($i=0; $i<count($s); $i++){

                $newstr .= $st[$i];

        }

        return $newsstr;

}

//简单编码函数(与php_decode函数对应)

function php_encode($str)

{

        if ($str==‘‘ && strlen($str)>128) return false;

 

        for($i=0; $i<strlen($str); $i++){

                $c = ord($str[$i]);

                if ($c>31 && $c<107) $c += 20;

                if ($c>106 && $c<127) $c -= 75;

                $word = chr($c);

                $s .= $word;

        }  

 

        return $s;  

}

//简单解码函数(与php_encode函数对应) 

function php_decode($str)

{

        if ($str==‘‘ && strlen($str)>128) return false;

 

        for($i=0; $i<strlen($str); $i++){

                $c = ord($word);

                if ($c>106 && $c<127) $c = $c-20;

                if ($c>31 && $c<107) $c = $c+75;

                $word = chr($c);

                $s .= $word;

        }  

 

        return $s;  

}

//简单加密函数(与php_decrypt函数对应) 

function php_encrypt($str)

{

        $encrypt_key = ‘abcdefghijklmnopqrstuvwxyz1234567890‘;

        $decrypt_key = ‘ngzqtcobmuhelkpdawxfyivrsj2468021359‘;

 

        if (strlen($str) == 0) return false;

 

        for ($i=0; $i<strlen($str); $i++){

                for ($j=0; $j<strlen($encrypt_key); $j++){

                        if ($str[$i] == $encrypt_key[$j]){

                                $enstr .= $decrypt_key[$j];

                                break;

                        }

                }

        }

 

       return $enstr;

}

//简单解密函数(与php_encrypt函数对应) 

function php_decrypt($str)

{

        $encrypt_key = ‘abcdefghijklmnopqrstuvwxyz1234567890‘;

        $decrypt_key = ‘ngzqtcobmuhelkpdawxfyivrsj2468021359‘;

 

        if (strlen($str) == 0) return false;

 

        for ($i=0; $i<strlen($str); $i++){

                for ($j=0; $j<strlen($decrypt_key); $j++){

                        if ($str[$i] == $decrypt_key[$j]){

                                $enstr .= $encrypt_key[$j];

                                break;

                        }

                }

        }

 

        return $enstr;

}

}

//单链表操作

#include <stdio.h>

#include <stdlib.h>

typedef char DataType;

typedef struct Node{

    DataType data;

    struct Node * Next;

}ListNode,* LinkList;

void Judement(LinkList head){ //判断分配内存

    if (!head){

        printf("Overflow.");

        exit(-1);

    }

}

LinkList CreatListF(void){ //头插法创建Single Linked List

    DataType ch;

    LinkList head = (ListNode*)malloc(sizeof(ListNode));

    Judement(head);

    ListNode* s;

    ch = getchar();

    while (ch != ‘\n‘){

        s = (ListNode*)malloc(sizeof(ListNode));

        Judement(s);

        s->data = ch;

        s->Next = head->Next;

        head->Next = s;

        ch = getchar();

    }

    return head;

}

LinkList CreatListS(void){ //尾插法创建Single Linked List

    char ch;

    ListNode* s;

    LinkList head = (ListNode*)malloc(sizeof(ListNode));

    Judement(head);

    ch = getchar();

    while (ch != ‘\n‘){

        s = (ListNode*)malloc(sizeof(ListNode));

        Judement(s);

        s->data = ch;

        head->Next = s;

        head = s;

        ch = getchar();

    }

    head->Next = NULL;

    return head;

}

int GetLength(LinkList head){  //获取长度

    int length = 0;

    LinkList p = head->Next;

    while (p){

        length += 1;

        p = p->Next;

    }

    return length;

}

ListNode* GetNodeById(LinkList head, int i){ //依序号查找元素

    if (i<1 || i>GetLength(head)){

        exit(1);

    }

    int j=1; //防止极端情况扫描逾界

    LinkList p = head->Next;

    while (p != NULL && j < i){

        j += 1;

        p = p->Next;

    }

    return p;

}

ListNode* GetNodeByValue(LinkList head, DataType e){ //依值查找元素

    LinkList p = head->Next;

    while (p != NULL&&p->data != e){

        p = p->Next;

    }

    return p;

}

int InsertList(LinkList head, DataType e, int i){ //插入e值在第i节点

    if (i<1 || i>GetLength(head) + 1){

        exit(1);

    }

    LinkList s = (ListNode*)malloc(sizeof(ListNode));

    s->data = e;

    LinkList q, p = head;

    int j = 1;

    while (j <= i){

        q = p;

        p = p->Next;

        j += 1;

    }

    s->Next = q->Next;

    q->Next = s;

    return 0;

}

int DeleteListNodeById(LinkList head, int i){ //依序号删除节点

    int j = 1;

    ListNode* p,* q;

    if (i<1 || i>GetLength(head)){

        exit(1);

    }

    p = head;

    while (j < i){

        p = p->Next;

        j += 1;

    }

    q = p->Next;

    p->Next = q->Next;

    free(q);

    return 0;

}

int DeleteListRepeatNode(ListNode* head){ //清除冗余数据

    ListNode* p, *q, *s;

    if (p == NULL){

        exit(1);

    }

    p = head->Next; //首节点无数据

    while (p->Next != NULL){

        q = p;

        while (q->Next != NULL){

            if (q->Next->data == p->data){

                s = q->Next;

                q->Next = q->Next->Next;

                free(s);

            }

            q = q->Next;

        }

        p = p->Next;

    }

    return 0;

}

以上是关于PHP实现基本算法代码的主要内容,如果未能解决你的问题,请参考以下文章

PHP实现四种基本排序算法

PHP实现四种基本排序算法

八大排序算法总结

PHP实现四种基本排序算法

PHP实现四种基本排序算法

php几种排序算法实例详解