Table of Contents
7种php基本排序实现方法,7种php排序
您可能感兴趣的文章:
Home php教程 php手册 7种php基本排序实现方法,7种php排序

7种php基本排序实现方法,7种php排序

Jun 13, 2016 am 08:44 AM
php sort

7种php基本排序实现方法,7种php排序

本文总结了一下常用的7种排序方法,并用php语言实现。

1、直接插入排序

/*
 *  直接插入排序,插入排序的思想是:当前插入位置之前的元素有序,
 *  若插入当前位置的元素比有序元素最后一个元素大,则什么也不做,
 *  否则在有序序列中找到插入的位置,并插入
 */
function insertSort($arr) {
  $len = count($arr);  
  for($i = 1; $i < $len; $i++) {
    if($arr[$i-1] > $arr[i]) {
      for($j = $i - 1;$j >= 0; $j-- ) {
        $tmp = $arr[$j+1];
        if($tmp < $arr[$j]) {
          $arr[$j+1] = $arr[$j];
          $arr[$j] = $tmp;
        }else{
          break;
        }          
      }  
    }
  }  
  return $arr;
}
Copy after login

2、冒泡排序

/*
  冒泡排序,冒泡排序思想:进行 n-1 趟冒泡排序, 每趟两两比较调整最大值到数组(子数组)末尾
*/
function bubbleSort($arr) {
  $len = count($arr);
  for($i = 1; $i < $len; $i++) {
    for($j = 0; $j < $len-$i; $j++) {
      if($arr[$j] > $arr[$j+1]) {
        $tmp = $arr[$j+1];
        $arr[$j+1] = $arr[$j];
        $arr[$j] = $tmp;
      }
    }
  }
  return $arr;
}
Copy after login

3、简单选择排序

/*
  简单选择排序, 简单排序思想:从数组第一个元素开始依次确定从小到大的元素
*/
function selectSort($arr) {
  $len = count($arr);
  for($i = 0; $i < $len; $i++) {
    $k = $i;
    for($j = $i+1; $j < $len; $j++) {
      if($arr[$k] > $arr[$j]) {
        $k = $j;
      }
    }
    if($k != $i) {
      $tmp = $arr[$i];
      $arr[$i] = $arr[$k];
      $arr[$k] = $tmp;
    }
  }
  return $arr;
}
Copy after login

4、希尔排序

/*
  希尔排序,希尔排序原理:将数组按指定步长分隔成若干子序列,然后分别对子序列进行排序(在这是直接)
*/
function shellSort($arr) {
  $len = count($arr);
  $k = floor($len/2);
  while($k > 0) {
    for($i = 0; $i < $k; $i++) {
      for($j = $i; $j < $len, ($j + $k) < $len; $j = $j + $k) {
        if($arr[$j] > $arr[$j+$k]) {
          $tmp = $arr[$j+$k];
          $arr[$j+$k] = $arr[$j];
          $arr[$j] = $tmp;
        }
      }
    }
    $k = floor($k/2);
  }
  return $arr;
}
Copy after login

5、快速排序

/*
 *  快速排序,快排思想:通过一趟排序将待排的记录分为两个独立的部分,其中一部分的记录的关键字均不大于
 *  另一部分记录的关键字,然后再分别对这两部分记录继续进行快速排序,以达到整个序列有序,具体做法需要
 *  每趟排序设置一个标准关键字和分别指向头一个记录的关键字和最后一个记录的关键字的指针。
 *  quickSort($arr, 0, count($arr) -1);
 */
function quickSort(&$arr,$low,$high) {
  if($low < $high) {
    $i = $low;
    $j = $high;
    $primary = $arr[$low];
    while($i < $j) {
      while($i < $j && $arr[$j] >= $primary) {
        $j--;
      }
      if($i < $j) {
        $arr[$i++] = $arr[$j];
      }
      while($i < $j && $arr[$i] <= $primary) {
        $i++;
      }
      if($i < $j) {
        $arr[$j--] = $arr[$i];
      }
    }
    $arr[$i] = $primary;
    quickSort($arr, $low, $i-1);
    quickSort($arr, $i+1, $high);
  }
}
Copy after login

6、堆排序

/*
  堆排序
*/

// 调整子堆的为大根堆的过程,$s为子堆的根的位置,$m为堆最后一个元素位置
function heapAdjust(&$arr, $s, $m) {
  $tmp = $arr[$s];
  // 在调整为大根堆的过程中可能会影响左子堆或右子堆
  // for循环的作用是要保证子堆也是大根堆
  for($j = 2*$s + 1; $j <= $m; $j = 2*$j + 1) {
    // 找到根节点的左右孩子中的最大者,然后用这个最大者与根节点比较,
    // 若大则进行调整,否则符合大根堆的 特点跳出循环  
    if($j < $m && $arr[$j] < $arr[$j+1]) {
      $j++;
    }
    if($tmp >= $arr[$j] ) {
      break;
    }
    $arr[$s] = $arr[$j];
    $s = $j;
  }
  $arr[$s] = $tmp;
}

// 堆排序
function heapSort($arr) {
  $len = count($arr);
  // 依次从子堆开始调整堆为大根堆
  for($i = floor($len/2-1); $i >= 0; $i--) {
    heapAdjust($arr, $i, $len-1);
  }
  // 依次把根节点调换至最后一个位置,再次调整堆为大根堆,找到次最大值,
  // 依次类推得到一个有序数组
  for($n = $len-1; $n > 0; $n--) {
    $tmp = $arr[$n];
    $arr[$n] = $arr[0];
    $arr[0] = $tmp;
    heapAdjust($arr, 0, $n-1);
  }
  return $arr;
}

Copy after login

7、归并排序

/*
  归并排序,这里实现的是两路归并
*/
// 分别将有序的$arr1[s..m]、$arr2[m+1..n]归并为有序的$arr2[s..n]
function Merge(&$arr1, &$arr2, $s, $m, $n) {
  for($k = $s,$i = $s, $j = $m+1; $i <= $m && $j <= $n; $k++) {
    if($arr1[$i]<$arr1[$j]) {
      $arr2[$k] = $arr1[$i++];
    }else {
      $arr2[$k] = $arr1[$j++];
    }
  }
  if($i <= $m) {
    for(; $i <= $m; $i++) {
      $arr2[$k++] = $arr1[$i];
    }
  } else if($j <= $n) {
    for(; $j <= $n; $j++) {
      $arr2[$k++] = $arr1[$j];
    }
  }
}

// 递归形式的两路归并
function MSort(&$arr1, &$arr2, $s, $t) {
  if($s == $t) {
    $arr2[$s] = $arr1[$s];
  }else {
    $m = floor(($s+$t)/2);
    $tmp_arr = array();
    MSort($arr1, $tmp_arr, $s, $m);
    MSort($arr1, $tmp_arr, $m+1, $t);
    Merge($tmp_arr, $arr2, $s, $m, $t);
  }
}

// 对一位数组$arr[0..n-1]中的元素进行两路归并
function mergeSort($arr) {
  $len = count($arr);
  MSort($arr, $arr, 0, $len-1);
  return $arr;
}

Copy after login

使用经验
若排序的记录数目n较小时,可以采用直接插入排序和简单选择排序,当记录本身信息量较大时,用简单选择排序方法较好。
若待排序记录按关键字基本有序,适合采用直接插入排序和冒泡排序。
若n值较大时,可以采用快速排序、堆排序和归并排序。另外快速排序被认为是内部排序方法中最好的方法。

以上就是本文的全部内容,希望对大家的学习有所帮助。

您可能感兴趣的文章:

  • PHP 数组排序方法总结 推荐收藏
  • PHP 多维数组的排序问题 根据二维数组中某个项排序
  • PHP 冒泡排序 二分查找 顺序查找 二维数组排序算法函数的详解
  • php二维数组排序详解
  • php二维数组排序方法(array_multisort usort)
  • php实现快速排序的三种方法分享
  • PHP二维数组排序的3种方法和自定义函数分享
  • php数组中包含中文的排序方法
  • PHP中的排序函数sort、asort、rsort、krsort、ksort区别分析
  • php中多维数组按指定value排序的实现代码
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)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles