这篇文章主要介绍了php选择排序法实现数组排序的方法,实例分析了选择排序的原理与具体执行步骤,具有一定参考借鉴价值,需要的朋友可以参考下
本文实例分析了php选择排序法实现数组排序的方法。分享给大家供大家参考。具体分析如下:
选择排序法的基本思路:直接用案例来说明吧,比如有一个数组$arr = array(2,6,3,9),从大到小排序。
第一次大循环:它首先假设$arr[0]为最大值,然后分别跟$arr[1]~$arr[3]进行比较,如果比较它大,则进行交换,过程是这样(2,6,3,9)---2和6比 --->(6,2,3,9)---6和3比--->(6,2,3,9)---6和9比--->(9,2,3,6)。注意,这里下标也要变化。
第二次大循环:假设$arr[1]最大(排除了$arr[0]),,分别跟$arr[2]~$arr[3]比较,过程是这样(9,2,3,6)----2和3比---->(9,3,2,6)---3和6比--->(9,6,2,3)。
第三次大循环:假设$arr[2]最大,跟$arr[3]比较,过程是这样(9,6,2,3)---2和3比--->(9,6,3,2)
同样的,经过 N-1 次大的循环,即可排列出来
PHP代码如下,这里同样用函数进行的封装
"; print_r($myarr); ?>
代码分析:
第一次大循环:
$i=0 数组(2,6,3,9)
$j=1,执行 2和6比:变成$arr[0]=6,$arr[1]=2,$max=6即(6,2,3,9)
$j=2,执行 3和6比:不执行
$j=3,执行 9和6比:变成$arr[0]=9,$arr[3]=6,$max=9即(9,2,3,6)
第二次大循环:
$i=1,$max=$arr[1]=2,数组(9,2,3,6)
$j=2,执行 3和2比:变成$arr[1]=3,$arr[2]=2,$max=3即(9,3,2,6)
$j=3,执行 6和3比:变成$arr[1]=6,$arr[3]=3,$max=6即(9,6,2,3)
第三次大循环:
$i=2,$max=$arr[2]=2,数组(9,6,2,3)
$j=3,执行 3和2比:变成$max[2]=3,$arr[3]=2,$max=3即(9,6,3,2)
希望本文所述对大家的php程序设计有所帮助。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

WebStorm Mac version
Useful JavaScript development tools