Home  >  Article  >  Backend Development  >  Code example for php implementation of selection sort

Code example for php implementation of selection sort

不言
不言forward
2019-01-26 10:30:483303browse

This article brings you code examples about PHP implementation of selection sorting. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Selection sort

Selection sort is a simple and intuitive sorting algorithm. Here's how it works. First, find the smallest (large) element in the unsorted sequence and store it at the beginning of the sorted sequence. Then, continue to find the smallest (large) element from the remaining unsorted elements, and then put it at the end of the sorted sequence. And so on until all elements are sorted.

The main advantage of selection sort has to do with data movement. If an element is in the correct final position, it will not be moved. Each time selection sort swaps a pair of elements, at least one of them will be moved to its final position, so sorting a list of n elements requires at most n -1 swaps in total. Among all the sorting methods that rely entirely on exchange to move elements, selection sorting is a very good one

Introduced in Wikipedia. Bubble sort and quick sort introduced in the first two articles are both sorting methods that rely entirely on exchange to move elements.

Animation demonstration

Code example for php implementation of selection sort

Code example for php implementation of selection sort

#Example

<?php $arr = [33, 24, 8, 21, 2, 23, 3, 32, 16];

function selectSort($arr)
{
    $count = count($arr);

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

    for ($i = 0; $i < $count - 1; $i++) {
        // 当前值的位置
        $key = $i;
        for ($k = $i + 1; $k < $count; $k++) {
            // 相邻值进行比较,条件成立替换当前值
            // 倒序 $arr[$key] < $arr[$k]
            if ($arr[$key] > $arr[$k]) {
                $key = $k;
            }
        }

        if ($key != $i) {
            // 交换位置
            $temp = $arr[$key];
            $arr[$key] = $arr[$i];
            $arr[$i] = $temp;
        }
    }

    return $arr;
}

print_r(selectSort($arr));
// Array ( [0] => 2 [1] => 3 [2] => 8 [3] => 16 [4] => 21 [5] => 23 [6] => 24 [7] => 32 [8] => 33 )

The above is the detailed content of Code example for php implementation of selection sort. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete