Home  >  Article  >  Backend Development  >  How to perform sorting algorithm and search algorithm in PHP?

How to perform sorting algorithm and search algorithm in PHP?

WBOY
WBOYOriginal
2023-05-20 16:32:021242browse

As a commonly used programming language, PHP has many built-in sorting and search algorithms to help developers process large amounts of data more efficiently. This article will introduce some common sorting algorithms and search algorithms and explain how to use them in PHP.

1. Sorting algorithm

  1. Bubble sort

Bubble sort is a basic sorting algorithm. Its principle is to sort adjacent The elements are compared in pairs and their positions are exchanged according to the size relationship to achieve the purpose of sorting. The specific implementation method is as follows:

function bubbleSort($arr) {
    $len = count($arr);

    for ($i = 0; $i < $len - 1; $i++) {
        for ($j = 0; $j < $len - $i - 1; $j++) {
            if ($arr[$j] > $arr[$j + 1]) {
                $temp = $arr[$j];
                $arr[$j] = $arr[$j + 1];
                $arr[$j + 1] = $temp;
            }
        }
    }

    return $arr;
}
  1. Quick sort

Quick sort is a commonly used sorting algorithm. Its principle is to select a benchmark value and sort the array to be sorted. It is divided into two parts that are smaller than the benchmark value and larger than the benchmark value, and then recursively perform quick sorting on these two parts, and finally merge the results to complete the sorting. The specific implementation method is as follows:

function quickSort($arr) {
    if (count($arr) < 2) {
        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));
}
  1. Merge sort

Merge sort is a classic sorting algorithm. Its principle is to continuously divide the array to be sorted into smaller ones. Subarrays until each subarray has only one element, then merge the two adjacent subarrays and sort them according to size relationship, repeat this process until the entire array is sorted. The specific implementation method is as follows:

function mergeSort($arr) {
    if (count($arr) < 2) {
        return $arr;
    }

    $mid = floor(count($arr) / 2);
    $left = array_slice($arr, 0, $mid);
    $right = array_slice($arr, $mid);

    return merge(mergeSort($left), mergeSort($right));
}

function merge($left, $right) {
    $result = [];

    while (count($left) && count($right)) {
        if ($left[0] <= $right[0]) {
            $result[] = array_shift($left);
        } else {
            $result[] = array_shift($right);
        }
    }

    while (count($left)) {
        $result[] = array_shift($left);
    }

    while (count($right)) {
        $result[] = array_shift($right);
    }

    return $result;
}

2. Search algorithm

  1. Sequential search

Sequential search is also called linear search. Its principle is to search from Starting from the first element of the array, each element is compared one by one to see if it is equal to the target value, until the target value is found or the end of the array is searched. The specific implementation method is as follows:

function linearSearch($arr, $target) {
    $len = count($arr);

    for ($i = 0; $i < $len; $i++) {
        if ($arr[$i] == $target) {
            return $i;
        }
    }

    return -1;
}
  1. Binary search

Binary search is also called half search. Its principle is to continuously reduce the search range to left and right for ordered arrays. Two parts, each time looking for the middle value of the array, if the middle value is greater than the target value, continue searching in the left half, otherwise continue searching in the right half until the target value is found or the search range is empty. The specific implementation method is as follows:

function binarySearch($arr, $target) {
    $low = 0;
    $high = count($arr) - 1;

    while ($low <= $high) {
        $mid = floor(($low + $high) / 2);
        if ($arr[$mid] < $target) {
            $low = $mid + 1;
        } else if ($arr[$mid] > $target) {
            $high = $mid - 1;
        } else {
            return $mid;
        }
    }

    return -1;
}

3. Summary

This article introduces common sorting algorithms and search algorithms, and provides sample codes for implementing these algorithms in PHP. Although PHP has many built-in sorting and search functions, understanding these algorithms can help deepen your understanding of data structures and algorithms and improve your programming skills. At the same time, in actual development, we can choose the most suitable algorithm according to specific needs to improve code efficiency and quality.

The above is the detailed content of How to perform sorting algorithm and search algorithm in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn