Several common sorting algorithms in PHP

Source: Internet
Author: User
Tags array length

<?php

In terms of time, quick sort and merge sort have advantages over time,
But it's not as good as sort, and merge sort is more memory-intensive!


$arr = [4,6,1,2,3,89,56,34,56,23,65];
/**
* Bubble Sort
* It repeatedly visits the sequence to sort, compares two elements at a time, and swaps them if their order is wrong.
* The work of the sequence of visits is repeated until there is no need to exchange, that is, the sequence has been sorted.
*/
function BUBBLESORTQ ($arr)
{
$len = Count ($arr);
Set an empty array to receive the bubbling

For ($i = 1; $i < $len; $i + +)//this layer loops to control the number of rounds that need to bubble
{
$flag = false; Before this sequencing begins, the swap flag should be false
This layer loop is used to control how many times a number needs to be compared per round
For ($k = 0; $k < $len-$i-1; $k + +)
{
Sort from small to large
If ($arr [$k] > $arr [$k + 1])
{
$tmp = $arr [$k + 1];
$arr [$k + 1] = $arr [$k];
$arr [$k] = $tmp;
$flag = true;
}
}
If (! $flag) return $arr;
}
}

Print_r (bubblesort ($arr));

/**
* Select sorting algorithm
* Each time a minimum (or maximum) element is selected from the data element to be sorted, it is stored at the starting position of the sequence until all the data elements to be sorted are Exhausted.
* Select Sort is an unstable sort method (such as sequence [5, 5, 3] The first time [5] is exchanged with [3], causing the first 5 to move to the second 5 Back)
*/
function Selectsort ($arr)
{
Define the variables to be exchanged
$temp = 0;
For ($i = 0; $i < count ($arr)-1; $i + +)
{
$minval = $arr [$i];//assumes $minval is the smallest value
$minvalIndex = $i;//subscript of minimum value
For ($j = $i + 1; $j < count ($arr); $j + +)
{
If ($minval > $arr [$j])//arrange from small to large
{
$minval = $arr [$j];//to Find the minimum value
$minvalIndex = $j;
}
}
$temp = $arr [$i];
$arr [$i] = $arr [$minvalIndex];
$arr [$minvalIndex] = $temp;
}
Return $arr;
}

Print_r (selectsort ($arr));

/**
* Insert Algorithm
* Each step inserts a record to be sorted by the size of its key value into the appropriate position in the previously sorted file until all is Inserted.
* The algorithm is suitable for ordering small amounts of data, and the time complexity is O (n^2). is a stable sorting method.
*/
function Insertsort ($arr)//order from small to large
{
First default $arr[0], already ordered, is an ordered table
For ($i = 1; $i < count ($arr); $i + +)
{
$insertval = $arr [$i];//$insertval is the number that is ready to be inserted
$insertIndex = number of subscripts to be compared $i -1;//ordered table
While ($insertIndex >= 0 && $insertval < $arr [$insertIndex])
{
$arr [$insertIndex + 1] = $arr [$insertIndex];//to Move the array backwards
$insertIndex--;//to move the subscript forward, ready to compare with the previous one
}
If ($insertIndex + 1!== $i)
{
$arr [$insertIndex + 1] = $insertval;
}
}
Return $arr;
}
Print_r (insertsort ($arr));


/*
* Quick Sort method
* Divide the sorted data into separate two parts by a single trip, and all of the data in one part is smaller than the rest of the Data.
* And then the two parts of the data are quickly sorted by this method, the whole sorting process can be recursive, in order to achieve the entire data into an ordered SEQUENCE.
*/
function QuickSort ($arr)
{
Determines whether an array
If (is_array ($arr))
{
Return false;
}
If the array length is 1, return directly
If (!isset ($arr [1]))
{
Return $arr;
}

$mid = $arr [0]; Gets a keyword for segmentation, typically the first element
$leftArray = Array ();
$rightArray = Array ();
foreach ($arr as $v)
{
If ($v > $mid)
{
$rightArray [] = $v; Put a number larger than $mid into an array.
}
If ($v < $mid)
{
$leftArray [] = $v; Put a number smaller than $mid in another array
}
}
$leftArray = QuickSort ($leftArray); Split the smaller array once again
$leftArray [] = $mid; Add the split element to the small array, and don't forget it.
$rightArray = QuickSort ($rightArray); Split the larger array once again
return Array_merge ($leftArray, $rightArray); Combination of two results
}
Print_r (quickSort ($arr));

/**
* Merge Sort
* Merge sort refers to the merging of two or more ordered series (or ordered tables) into a sequence (or ordered Table) that is still ordered.
* This sort method is often used to merge multiple sequential data files into an ordered data file.
*/
function MergeSort (& $arr)
{
$len = Count ($arr);//find array length
Msort ($arr, 0, $len-1);
Return $arr;
}
A program that actually implements merge sort
function Msort (& $arr, $left, $right)
{
If ($left < $right)
{
Note that there are 1 extra elements in the subsequence, then you need to split them, sort them separately,
Consolidation of Split positions, LENGTH/2 rounding
$center = Floor (($left + $right)/2);
Recursive call to reorder left
Msort ($arr, $left, $center);
Recursive call to the right to reorder again
Msort ($arr, $center + 1, $right);
Merge sort Results
Mergearray ($arr, $left, $center, $right);
}
}
Two ordered arrays merged into an ordered array
function Mergearray (& $arr, $left, $center, $right)
{
Set two start position markers
$a _i = $left;
$b _i = $center + 1;
While ($a _i <= $center && $b _i <= $right)
{
When arrays A and array B are not crossed
If ($arr [$a _i] < $arr [$b _i])
{
$temp [] = $arr [$a _i++];
}
Else
{
$temp [] = $arr [$b _i++];
}
}
Determine if the elements in array A are exhausted, and insert them all into the C array without
While ($a _i <= $center)
{
$temp [] = $arr [$a _i++];
}
Determine if the elements in array A are exhausted, and insert them all into the C array without
While ($b _i <= $right)
{
$temp [] = $arr [$b _i++];
}
Writes a sorted part of the $ARRC to the $arr
For ($i = 0, $len = Count ($temp); $i < $len; $i + +)
{
$arr [$left + $i] = $temp [$i];
}
}

Print_r (mergesort ($arr));


/*
* Hill Sort
* Separates the array into several sub-sequences by the specified step, and then sorts the sub-sequences separately (in this is Direct)
*/
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;
}

Print_r (shellsort ($arr));

/*
* Heap Sorting
* Adjust the Dagen process for the sub-heap, $s the location of the root of the sub-heap, $m the last element position of the heap
*/


function Heapadjust (& $arr, $s, $m)
{
$tmp = $arr [$s];
The left or right child heap may be affected in the process of tuning to Dagen
The purpose of the For loop is to ensure that the sub-heap is also Dagen
For ($j = $s + 1, $j <= $m; $j = $j + 1)
{
Find the largest of the left and right children of the root node and compare it with the root node,
If the big is adjusted, otherwise meet the characteristics of Dagen jump out of the loop
If ($j < $m && $arr [$j] < $arr [$j + 1])
{
$j + +;
}
If ($tmp >= $arr [$j])
{
Break
}
$arr [$s] = $arr [$j];
$s = $j;
}
$arr [$s] = $tmp;
}
Heap Sort
function Heapsort ($arr)
{
$len = Count ($arr);
Adjust the heap to a large heap starting from the child heap
For ($i = Floor ($len/2-1); $i >= 0; $i-)
{
Heapadjust ($arr, $i, $len-1);
}
Switch the root node to the last position, then resize the heap to a large heap again, and find the secondary maximum Value.
Get an ordered array by analogy
For ($n = $len-1; $n > 0; $n--)
{
$tmp = $arr [$n];
$arr [$n] = $arr [0];
$arr [0] = $tmp;
Heapadjust ($arr, 0, $n-1);
}
Return $arr;
}
Print_r (heapsort ($arr));

Several common sorting algorithms in PHP

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.