Insert sort and quick sort for arrays

Source: Internet
Author: User
Tags array sort arrays
Preface

About the sorting of the array, there are many methods in the algorithm, more simple bubble, selection, insertion and other familiar arithmetic methods, in today's pursuit of efficiency of the society, the quality of the algorithm has an important impact on the program itself. When we determine the quality of the algorithm, time complexity is an important ruler,

In an array sort, the efficiency of inserting sort and quick sorting is more efficient than bubbling and sorting, and today comes a chat about the principles and implementations of insert sorting and quick sorting.

Insert Sort

The basic operation of inserting a sort is to insert a data into the ordered sorted data, to get a new ordered data, to divide the sorted array into two parts: the first part contains all the elements of the array, except for the last element (where the array has more space to insert), The second part contains only this element (that is, the element to be inserted). After the first part is sorted, the last element is inserted into the first part of the sequence.


Schematic diagram

The easy-to-understand saying is:

We sort the arrays so that the first number in the array can be thought of as an ordered array, and the subsequent number is an unordered array. After iterating through the unordered array and comparing it with the previous ordered array, the ordered array moves back one bit to insert the data when it is discovered that it needs to be inserted.

Case list (from small to large sort):

has an array:

$arr = Array (1,2,10,5,3);

Suppose that the first number 1 is an ordered array. That

Ordered (1) unordered (2, 10, 5, 3);

Traversing unordered arrays

for ($i = 1; $i < $total; $i + +) {
	$insert = $arr [$i];//first record the data with insert;
	$j = $i-1;

Use a while loop to determine where to insert

while ($j >= 0 && $arr [$j] > $insert) {

The judging condition $j must be greater than or equal to 0, the number of the current polygon has been ordered is larger than the number to be sorted, which is the need for the previous number to move backward one namely:

$arr [$j + 1] = $arr [$j];
		$j--;

Don't worry here $arr[$i] is overwritten, we've recorded the value to be sorted after the for loop.

Jumps out of the loop when the loop judgment condition is not satisfied and assigns a value

$arr [$j + 1] = $insert;

Here you can judge when there is no loop, $j + 1 = $i No assignment is necessary at this time.

Code:

<?php
        $arr = Array (1,2,10,5,3);
	Function Insertsort (& $arr) {
		$total = count ($arr);
		for ($i = 1; $i < $total; $i + +) {
			$insert = $arr [$i];//first record the data with insert;
			$j = $i-1;
			while ($j >= 0 && $arr [$j] > $insert) {
				$arr [$j + 1] = $arr [$j];
				$j--;
			}
			if ($j +1! = $i) {
				$arr [$j + 1] = $insert;
			}}
	}
        Insertsort ($arr);
        Echo ' <pre> ';
        Var_dump ($arr);

Digital Process diagram:



The time complexity for inserting a sort is O (n^2). is a stable sorting method.

Quick Sort

By sorting the sorted data into separate two parts, one part of all data is smaller than the other part of the data, and then the two parts of the data are quickly sorted by this method, the entire sorting process can be recursive, so as to achieve the entire data into an ordered sequence.


Examples of quick sorting:

has an array:

$arr = Array (6,2,7,3,8,9);

We select the first number to be bounded:

$k = $arr [0];//records the value of K  to divide the array into two parts, smaller than K on the left, larger than K on the right.

Defines two arrays a value that stores a number smaller than k, and a value that stores larger than K.

The array is then traversed, compared to the value of the $k, and after the traversal is completed, the array is decomposed using recursion, until it can no longer be decomposed.

$x =quicksort ($x);
$y =quicksort ($y);
Return Array_merge ($x, Array ($k), $y);//array merge.

Code (one that is easy to understand):

<?php


    $arr = Array (6,2,7,3,8,9);
    Function QuickSort (& $arr) {
        if (count ($arr) >1) {
            $k = $arr [0];//record K's value divides the  array into two parts, smaller than K on the left, larger than K on the right.
            $x =array ();
            $y =array ();
            $_size=count ($arr);
            for ($i =1; $i <$_size; $i + +) {
                if ($arr [$i]<= $k) {
                    $x []= $arr [$i];
                } else if ($arr [$i]> $k) {
                    $y []= $arr [$i];
                }
            }
            $x =quicksort ($x);
            $y =quicksort ($y);
            Return Array_merge ($x, Array ($k), $y);//array merge.
        }else{
            return $arr;
        }
    }
    Echo ' <pre> ';
    Var_dump (QuickSort ($arr));

(Note: This approach, while conforming to the idea of fast sequencing, creates a large number of array-holding data in the recursive process, resulting in a allowed memory size of 134217728 bytes exhausted, which is memory exhaustion, when the data volume is large) summary /c24> insertion Sorting and quick sorting: the efficiency of inserting a sort is less efficient than a quick sort. We can use one to store 200,000 data arrays and compare them in two different ways.

<span style= "FONT-SIZE:18PX;" >        $arr  = Array ();
	for ($i = 0; $i < 200000; $i + +) {
		$arr [] = rand (1, +);
	} </span>

By comparison of time before and after execution

Insert Sort:


Quick sort:


You can see that the execution time of the insert sort exceeds the default time of PHP. And the quick sort took 7 seconds.




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.