Common sorting algorithms and binary search in php

Source: Internet
Author: User

Common sorting algorithms and binary search in php

I. Merge Sorting

Combine Two ordered series into an ordered series, which we call"Merge".
Merge Sort uses the Merge idea to Sort the series. According to the specific implementation, the Merge Sorting includes"From top down"And"From bottom up"Two methods.


1.Sort from bottom to top: Divide the series to be sorted into several sub-series with a length of 1, and then merge these series into two. Then, combine these two sub-series with a length of 2; obtain several 4-length ordered series, and then merge them into two columns. Directly merge them into a sequence. In this way, the sorting result we want is obtained.

2.Sort from top to bottom: It is in reverse order with "from bottom to top. It consists of three steps:
① Decomposition -- split the current interval into two parts, that is, find the split point mid = (low + high)/2;
② Solving -- recursively sort the two subintervals a [low... mid] And a [mid + 1... high. The recursion termination condition is that the length of the subinterval is 1.
③ Merge -- merge the sorted subintervals a [low... mid] And a [mid + 1... high] is merged into an ordered Range a [low... high].

/*** Merge Sorting implementation process * @ param Array $ arr range Array to be sorted * @ param Int $ start position of the first range Array * @ param Int $ mid first end position of the range array, start position of the second range Array * @ param Int $ end position of the second range Array * @ return void */function merge (Array & $ arr, $ start, $ mid, $ end) {$ I = $ start; $ j = $ mid + 1; $ k = 0; while ($ I <= $ mid & $ j <= $ end) {if ($ arr [$ I] <= $ arr [$ j]) // you can specify the data size of each array, and category $ tmp [$ k ++] = $ arr [$ I ++]; else $ tmp [$ k ++] = $ arr [$ j ++];} while ($ I <= $ Mid) // prevents data from being classified in the first interval. $ tmp [$ k ++] = $ arr [$ I ++] while ($ j <= $ end) // prevent data from being classified in the second interval $ tmp [$ k ++] = $ arr [$ j ++]; // integrate all the sorted elements into the array arr. For ($ I = 0; $ I <$ k; ++ $ I) $ arr [$ start + $ I] = $ tmp [$ I];} /*** merge and sort (from top to bottom) * @ param Array $ Array to be sorted * @ param Int $ start Array start position * @ param Int end Array end position * @ return void */function merge_sort (Array & $ arr, $ start = 0, $ end = 0) {$ len = count ($ arr); if ($ len <= 1 | $ start >=$ end) return $ arr; $ mid = intval ($ start + $ end)/2); // interval merge_sort ($ arr, $ start, $ mid); merge_sort ($ arr, $ mid + 1, $ end); merge ($ arr, $ start, $ mid, $ end );}

// The opposite is true from bottom up.

Ii. Quick sorting

Data to be sorted is divided into two independent parts by one sort. All the data in one part is smaller than all the data in the other part, then, sort the two data parts by using this method. The entire sorting process can be recursive to convert the entire data into an ordered sequence. The Time Calculation of the fast sorting subject algorithm is about O (log2n), and the number of functions in the partition is about O (n). Therefore, the total time complexity is O (nlog2n ), it is obviously better than Bubble Sorting O (n2 ). however, the advantages of algorithms are not absolute. In the trial analysis, when the keywords of the original file are ordered, the complexity of the quick sorting time is O (n2), which is not fast. In this case, the Bubble Sorting is O (n), but it is very fast. Among the multiple sorting methods when the original file record keywords are unordered, quick sorting is considered as the best sorting method.

/*** Quick Sort ** @ param Array $ Array to be sorted * @ return Array */function quick_sort (Array $ arr) {$ len = count ($ arr); if ($ len <= 1) return $ arr; $ tmp = $ arr [0]; $ left_arr = []; $ right_arr = []; for ($ I = 1; $ I <$ len; ++ $ I) {if ($ arr [$ I] <= $ tmp) $ left_arr [] = $ arr [$ I]; else $ right_arr [] = $ arr [$ I];} // recursive classification $ left_arr = quick_sort ($ left_arr ); $ right_arr = quick_sort ($ right_arr); return array_merge ($ left_arr, array ($ tmp), $ right_arr );}

Iii. Bubble Sorting

Compare the size of the elements to be sorted. If the two data elements are in the opposite order, they are exchanged until there is no reverse order of the data elements. The time complexity of this algorithm is O (n2 ). However, when the sequence of the original keywords is ordered, only one comparison is completed, and the time complexity is O (n ).

/*** Bubble sort ** @ param Array $ Array to be sorted * @ return Array */function bubble_sort (Array $ arr) {$ len = count ($ arr); for ($ I = 0; $ I <$ len; ++ $ I) {for ($ j = $ len-1; $ j> $ I; -- $ j) {if ($ arr [$ j] <$ arr [$ J-1]) {$ tmp = $ arr [$ j]; $ arr [$ j] = $ arr [$ J-1]; $ arr [$ J-1] = $ tmp ;}} return $ arr ;}

Iv. Insert sorting

Each time, a data element to be sorted is inserted into the sequence that has already been sorted, so that the sequence is still ordered, until all the elements of the data to be sorted are inserted. If the target is to sort the sequences of n elements in ascending order, there are best cases and worst cases of adopting insert sorting. The best case is that the sequence is already in ascending order. In this case, the comparison operation needs to be performed (n-1) times. The worst case is that the sequence is sorted in descending order. At this time, we need to compare n (n-1)/two times. The value assignment operation for insert sorting adds (n-1) the number of comparison operations. On average, the time complexity of inserting a sorting algorithm is O (n ^ 2 ). Therefore, insert sorting is not suitable for sorting applications with large data volumes. However, if the amount of data to be sorted is small, for example, if the order is smaller than, insertion sorting is still a good choice.

/*** Insert sorting ** @ param Array $ Array to be sorted * @ return Array */function insert_sort (Array $ arr) {$ len = count ($ arr); for ($ I = 1; $ I <$ len; ++ $ I) {$ tmp = $ arr [$ I]; $ j = $ I-1; // insert data to a proper position (switching location) while ($ j >=0 & $ arr [$ j]> $ tmp) {$ arr [$ j + 1] = $ arr [$ j]; $ arr [$ j] = $ tmp; -- $ j ;}} return $ arr ;}

5. Select sorting

Each trip selects the smallest (or largest) element from the data element to be sorted, and places it at the end of the sorted series until all the data elements to be sorted are arranged. The time complexity is o (n2), which is not stable and suitable for small scale

/*** Select sort * @ param Array $ Array to be sorted * @ return Array */function select_sort (Array $ arr) {$ len = count ($ arr); for ($ I = 0; $ I <$ len; ++ $ I) {$ k = $ I; // mark the current index for ($ j = $ I + 1; $ j <$ len; ++ $ j) {if ($ arr [$ j] <$ arr [$ k]) $ k = $ j; // obtain the current minimum index if ($ k! = $ I) // if the index with the minimum value changes {$ tmp = $ arr [$ I]; $ arr [$ I] = $ arr [$ k]; $ arr [$ k] = $ tmp ;}} return $ arr ;}

6. Binary Search

/*** Binary Search * @ param Array $ Array to be searched * @ param Int $ key the keyword to be searched * @ return Int */function bin_search (Array $ arr, $ key) {$ high = count ($ arr); if ($ high <= 0) return 0; $ low = 0; while ($ low <= $ high) {// arr [low .. high] non-empty $ mid = intval ($ low + $ high)/2); if ($ arr [$ mid] ==$ key) return $ mid; // if ($ arr [$ mid]> $ key) $ high = $ mid-1 is returned. // continue on the arr [low .. in mid-1], find else $ low = $ mid + 1; // continue to the arr [mid + 1 .. search in high]} return 0; // when low> high, it indicates that the search interval is empty. Search Failed} $ arr = array (100,110 ); echo bin_search ($ arr, 80 );

 

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.