Home Backend Development PHP Tutorial PHP sorting implementation

PHP sorting implementation

Aug 08, 2016 am 09:30 AM
arr array count return

<?php
002
/**
003
 * 插入排序(一维数组)
004
 * 每次将一个待排序的数据元素,插入到前面已经排好序的数列中的适当的位置,使数列依然有序;直到待排序的数据元素全部插入完成为止。
005
 */
006
function insertSort($arr) {
007
    if (!is_array($arr) || count($arr) == 0) {
008
        return $arr;
009
    }
010
    $count = count($arr);
011
    for ($i = 1; $i < $count; $i++) {
012
        if (isset($arr[$i])) {
013
            $tmp = $arr[$i]; //获取后一个元素的值
014
            $j = $i - 1; //获取前面的下标
015
            while ($arr[$j] > $tmp) { //如果前面一个比后面一个大, 这里是从小到大
016
                $arr[$j + 1] = $arr[$j]; //把小的元素和前面的对换,直到移动到合适的位置,在移动下一个
017
                $arr[$j] = $tmp;
018
                $j--;
019
            }
020
        }
021
    }
022
    return $arr;
023
}
024
 
025
/**
026
 * 选择排序(一维数组)
027
 * 每一趟从待排序的数据元素中选出最小(最大)的一个元素,顺序放在已排好序的数列的最后,直到全部待排序的数据元素排完。
028
 */
029
function selectSort($arr) {
030
    if (!is_array($arr) || count($arr) == 0) {
031
        return $arr;
032
    }
033
    $count = count($arr);
034
    for ($i = 0; $i < $count; $i++) {
035
        $k = $i;
036
        for ($j = $i + 1; $j < $count; $j++) {
037
            if ($arr[$k] > $arr[$j])
038
                $k = $j; //找出最小的
039
            if ($k != $i) {
040
                $tmp = $arr[$i];
041
                $arr[$i] = $arr[$k];
042
                $arr[$k] = $tmp;
043
            }
044
        }
045
    }
046
    return $arr;
047
}
048
 
049
/**
050
 * 冒泡排序(一维数组)
051
 * 两两比较待排序数据元素的大小,发现两个数据元素的次序相反即进行交换,直到没有反序的数据元素为止
052
 */
053
function bubbleSort($array) {
054
    $count = count($array);
055
    if ($count <= 0) {
056
        return false;
057
    }
058
    for ($i = 0; $i < $count; $i++) {
059
        for ($j = $count - 1; $j > $i; $j--) {
060
            if ($array[$j] < $array[$j - 1]) { //比较找到的数进行交换
061
                $tmp = $array[$j];
062
                $array[$j] = $array[$j - 1];
063
                $array[$j - 1] = $tmp;
064
            }
065
        }
066
    }
067
    return $array;
068
}
069
 
070
/**
071
 * 快速排序(一维数组)
072
 */
073
function quickSort($array) {
074
    if (count($array) <= 1) {
075
        return $array;
076
    }
077
    $key = $array[0];
078
    $left_arr = array();
079
    $right_arr = array();
080
    for ($i = 1; $i < count($array); $i++) {
081
        if ($array[$i] <= $key) {
082
            $left_arr[] = $array[$i];
083
        } else {
084
            $right_arr[] = $array[$i];
085
        }
086
    }
087
    $left_arr = quickSort($left_arr);
088
    $right_arr = quickSort($right_arr);
089
    return array_merge($left_arr, array(
090
            $key
091
    ), $right_arr);
092
}
093
 
094
/**
095
 * 按照元素的值进行排序
096
 * strOrder 为排列的顺序 asc 升序 desc 降序
097
 */
098
function sortByVal($arr, $strOrder = &#39;asc&#39;) {
099
    if (!is_array($arr) || count($arr) == 0) {
100
        return $arr;
101
    }
102
 
103
    $arrReturn = array();
104
    foreach ($arr as $key => $val) {
105
        $arrKey[] = $key;
106
        $arrVal[] = $val;
107
    }
108
 
109
    $count = count($arrVal);
110
    if ($count) {
111
        //创建key的顺序数组
112
        for ($key = 0; $key < $count; $key++) {
113
            $arrKeyMap[$key] = $key;
114
        }
115
        //对值进行排序
116
        for ($i = 0; $i < $count; $i++) {
117
 
118
            for ($j = $count - 1; $j > $i; $j--) {
119
                //<从小到大排列 升降在这修改
120
                $bol = $strOrder == &#39;asc&#39; ? $arrVal[$j] < $arrVal[$j - 1] : $arrVal[$j] > $arrVal[$j - 1];
121
                if ($bol) {
122
                    $tmp = $arrVal[$j];
123
                    $arrVal[$j] = $arrVal[$j - 1];
124
                    $arrVal[$j - 1] = $tmp;
125
                    //值的冒泡排序,引起key的数组的交互
126
                    $keytmp = $arrKeyMap[$j];
127
                    $arrKeyMap[$j] = $arrKeyMap[$j - 1];
128
                    $arrKeyMap[$j - 1] = $keytmp;
129
                }
130
            }
131
        }
132
        if (count($arrKeyMap)) {
133
            foreach ($arrKeyMap as $val) {
134
                $arrReturn[] = $arrKey[$val];
135
            }
136
        }
137
        return $arrReturn;
138
    }
139
}
140
 
141
/**
142
 * 使用原生的函数进行数组按照值进行排列
143
 */
144
function arraySortByVal($arr, $keys, $type = 'asc') {
145
    $keysvalue = $new_array = array();
146
    foreach ($arr as $k => $v) {
147
        $keysvalue[$k] = $v[$keys];
148
    }
149
    if ($type == 'asc') {
150
        asort($keysvalue);
151
    } else {
152
        arsort($keysvalue);
153
    }
154
    reset($keysvalue);
155
    foreach ($keysvalue as $k => $v) {
156
        $new_array[$k] = $arr[$k];
157
    }
158
    return $new_array;
159
}
Copy after login

j

The above introduces the PHP sorting implementation, including aspects of the content. I hope it will be helpful to friends who are interested in PHP tutorials.

Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Detailed explanation of the usage of return in C language Detailed explanation of the usage of return in C language Oct 07, 2023 am 10:58 AM

The usage of return in C language is: 1. For functions whose return value type is void, you can use the return statement to end the execution of the function early; 2. For functions whose return value type is not void, the function of the return statement is to end the execution of the function. The result is returned to the caller; 3. End the execution of the function early. Inside the function, we can use the return statement to end the execution of the function early, even if the function does not return a value.

What is the execution order of return and finally statements in Java? What is the execution order of return and finally statements in Java? Apr 25, 2023 pm 07:55 PM

Source code: publicclassReturnFinallyDemo{publicstaticvoidmain(String[]args){System.out.println(case1());}publicstaticintcase1(){intx;try{x=1;returnx;}finally{x=3;}}}#Output The output of the above code can simply conclude: return is executed before finally. Let's take a look at what happens at the bytecode level. The following intercepts part of the bytecode of the case1 method, and compares the source code to annotate the meaning of each instruction in

The difference between counta and count The difference between counta and count Nov 20, 2023 am 10:01 AM

The Count function is used to count the number of numbers in a specified range. It ignores text, logical values, and null values, but counts empty cells. The Count function only counts the number of cells that contain actual numbers. The CountA function is used to count the number of non-empty cells in a specified range. It not only counts cells containing actual numbers, but also counts the number of non-empty cells containing text, logical values, and formulas.

Sort array using Array.Sort function in C# Sort array using Array.Sort function in C# Nov 18, 2023 am 10:37 AM

Title: Example of using the Array.Sort function to sort an array in C# Text: In C#, array is a commonly used data structure, and it is often necessary to sort the array. C# provides the Array class, which has the Sort method to conveniently sort arrays. This article will demonstrate how to use the Array.Sort function in C# to sort an array and provide specific code examples. First, we need to understand the basic usage of the Array.Sort function. Array.So

How to use the array_combine function in PHP to combine two arrays into an associative array How to use the array_combine function in PHP to combine two arrays into an associative array Jun 26, 2023 pm 01:41 PM

In PHP, there are many powerful array functions that can make array operations more convenient and faster. When we need to combine two arrays into an associative array, we can use PHP's array_combine function to achieve this operation. This function is actually used to combine the keys of one array as the values ​​of another array into a new associative array. Next, we will explain how to use the array_combine function in PHP to combine two arrays into an associative array. Learn about array_comb

Simple and clear method to use PHP array_merge_recursive() function Simple and clear method to use PHP array_merge_recursive() function Jun 27, 2023 pm 01:48 PM

When programming in PHP, we often need to merge arrays. PHP provides the array_merge() function to complete array merging, but when the same key exists in the array, this function will overwrite the original value. In order to solve this problem, PHP also provides an array_merge_recursive() function in the language, which can merge arrays and retain the values ​​of the same keys, making the program design more flexible. array_merge

How does Vue3 use setup syntax sugar to refuse to write return How does Vue3 use setup syntax sugar to refuse to write return May 12, 2023 pm 06:34 PM

Vue3.2 setup syntax sugar is a compile-time syntax sugar that uses the combined API in a single file component (SFC) to solve the cumbersome setup in Vue3.0. The declared variables, functions, and content introduced by import are exposed through return, so that they can be used in Vue3.0. Problems in use 1. There is no need to return declared variables, functions and content introduced by import during use. You can use syntactic sugar //import the content introduced import{getToday}from'./utils'//variable constmsg='Hello !'//function func

Use the return keyword in JavaScript Use the return keyword in JavaScript Feb 18, 2024 pm 12:45 PM

Usage of return in JavaScript requires specific code examples In JavaScript, the return statement is used to specify the value returned from a function. Not only can it be used to end the execution of a function, it can also return a value to the place where the function was called. The return statement has the following common uses: Return a value The return statement can be used to return a value to the place where the function is called. Here is a simple example: functionadd(a,b){

See all articles