The sorting and search algorithms are put together just now, which makes it inconvenient to read. Therefore, we will use the search algorithms for discussion. php implements binary search based on quick sorting.
/*** Description: PhP class that implements the binary search algorithm * @ author wzy */class binary_search {public $ arr; Public $ key; function _ construct ($ arr, $ key) {// The array initialized here is already an ordered array $ this-> arr = $ arr; $ this-> key = $ key;} function binarysearch () {$ start = 0; $ end = count ($ this-> ARR)-1; while ($ start <= $ end) {// The value of mid can be an upper or lower integer $ mid = Ceil ($ start + $ end)/2 ); // $ mid = ($ start + $ end)> 1; // $ mid = intval ($ start + $ end)/2 ); if ($ this-> arr [$ mid] <$ this-> key) {$ start = $ Mid + 1 ;} else if ($ this-> arr [$ mid]> $ this-> key) {$ end = $ mid-1 ;}else {return $ mid ;}}}}You may also encounter this situation. The elements in the array have repeated data, and the position of the first element in the repeated data needs to be returned, for example, $ arr = array, 6, 6, 6, 7, 8); when searching for 6, the returned position should be 5, rather than other (the subscript starts counting from 0), so you need to judge in the returned mid, the Code is as follows:
/*** Description: PhP class that implements the binary search algorithm * @ author wzy */class binary_search {public $ arr; Public $ key; function _ construct ($ arr, $ key) {// The array initialized here is already an ordered array $ this-> arr = $ arr; $ this-> key = $ key;} function binarysearch () {$ start = 0; $ end = count ($ this-> ARR)-1; while ($ start <= $ end) {// The value of mid can be an upper or lower integer $ mid = Ceil ($ start + $ end)/2 ); // $ mid = ($ start + $ end)> 1; // $ mid = intval ($ start + $ end)/2 ); if ($ this-> arr [$ mid] <$ this-> key) {$ start = $ Mid + 1 ;} else if ($ this-> arr [$ mid]> $ this-> key) {$ end = $ mid-1 ;} else {// returns the first matched element for ($ I = $ mid-1; $ I >=0; $ I --) {if ($ this-> arr [$ I] ==$ this-> key) {$ mid = $ I;} else {break ;}} return $ mid ;}}}}