PHP indexed array sorting method sorting (bubble, select, insert, fast)

1. Bubble sort

1. Principle

        Each time, two adjacent numbers are compared in sequence in the unordered queue, the decimals are swapped to the front, and the comparison is performed successively until the largest number is moved to the end. Continue to compare the remaining N-1 numbers, and move the next largest number to the penultimate digit. Follow this rule until the end of the comparison.

2. Code

/**
* Bubble Sort
* @param Array sort array
* @return Array array of sort numbers
*/
function bubbleSort($arr)
{  
  $len=count($arr);
  //This layer loop controls the number of rounds that need to be bubbling
  for($i=1;$i<$len;$i++)
  { //This layer of loop is used to control the number of times that a number needs to be compared in each round
    for($k=0;$k<$len-$i;$k++)
    {
       if($arr[$k]>$arr[$k+1])
        {
            $tmp=$arr[$k+1];
            $arr[$k+1]=$arr[$k];
            $arr[$k]=$tmp;
        }
    }
  }
  return $arr;
}

Second, the selection sort

1. Principle

        Each time, the minimum value is "selected" in the unordered queue, placed at the end of the ordered queue, and the value is removed from the unordered queue (the specific implementation is slightly different).

2. Code

/**
* selection sort
* Function: Rearrange the index array (values ​​are also numbers) in the order of [key=>value:minimum key=>minimum]
* @param   Array
* @return  Array
*/
function selectSort($arr) {
	//The double loop is completed, the outer layer controls the number of rounds, and the inner layer controls the number of comparisons
 	$len=count($arr);
    for($i=0; $i<$len-1; $i++) {
        //First assume the position of the smallest value
        $p = $i;
        
        for($j=$i+1; $j<$len; $j++) {
            //$arr[$p] is the currently known minimum value
            if($arr[$p] > $arr[$j]) {
            //Compare, find smaller, record the position of the minimum value; and use the known minimum value for comparison in the next comparison.
                $p = $j;
            }
        }
        //The position of the current minimum value has been determined and saved to $p. If the position of the minimum value is found to be different from the currently assumed position $i, the positions can be exchanged.
        if($p != $i) {
            $tmp = $arr[$p];
            $arr[$p] = $arr[$i];
            $arr[$i] = $tmp;
        }
    }
    //return the final result
    return $arr;
}

3. Insertion sort

1. Principle

        Always define the first element as ordered, and insert the elements into the ordered arrangement one by one. The feature is to constantly move the data, vacate an appropriate position, and put the elements to be inserted into it.

2. Code:

/**
* Insertion sort
* Function: Rearrange the index array (values ​​are also numbers) in the order of [key=>value:minimum key=>minimum]
* @param Array
* @return Array
*/
function insertSort($arr) {
    $len=count($arr);
    for($i=1; $i<$len; $i++) {
        $tmp = $arr[$i];
        //Inner loop control, compare and insert
        for($j=$i-1;$j>=0;$j--) {
            if($tmp < $arr[$j]) {
                // Find that the inserted element is smaller, exchange the position, and exchange the element at the back with the element at the front
                $arr[$j+1] = $arr[$j];
                $arr[$j] = $tmp;
            }
            else {
                //If you encounter an element that does not need to be moved, since it is already sorted into an array, the previous one does not need to be compared again.
                break;
            }
        }
    }
    return $arr;
}

4. Quick Sort

/**
* Quick sort
* Function: Always define the first element as ordered, insert the elements one by one into the ordered arrangement, which is characterized by constantly moving data, vacating an appropriate position, and placing the elements to be inserted into it .
* @param Array
* @return Array
*/
function quickSort($arr) {
    //First determine if you need to continue
    $length = count($arr);
    if($length <= 1) {
        return $arr;
    }
    //select the first element as the benchmark
    $base_num = $arr[0];
    // Traverse all elements except the ruler and put them into two arrays according to the size relationship
    //initialize two arrays
    $left_array = array(); // less than the benchmark
    $right_array = array(); // greater than the benchmark
    for($i=1; $i<$length; $i++) {
        if($base_num > $arr[$i]) {
            // put in the left array
            $left_array[] = $arr[$i];
        }
        else{
            // put on the right
            $right_array[] = $arr[$i];
        }
    }
    //Then the left and right arrays are sorted in the same way, and this function is called recursively
    $left_array = quickSort($left_array);
    $right_array = quickSort($right_array);

    //merge
    return array_merge($left_array, array($base_num), $right_array);
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325851367&siteId=291194637