PHP quick sorting small example php quick sorting implementation method
|
PHP quick sorting small example php quick sorting implementation method
Complete code:
- Set_time_limit (0 );
- Function quickSort ($ arr ){
- If (count ($ arr)> 1) {// only determines if the array length is greater than 1
- $ K = $ arr [0]; // the default reference object is the first object in the array.
- $ X = array (); // smaller than the reference
- $ Y = array (); // greater than the reference
- $ _ Size = count ($ arr );
- For ($ I = 1; $ I <$ _ size; $ I ++ ){
- If ($ arr [$ I] <= $ k ){
- $ X [] = $ arr [$ I];
- } Else {
- $ Y [] = $ arr [$ I];
- }
- }
- // Recursively arrange arrays on both sides
- $ X = quickSort ($ x );
- $ Y = quickSort ($ y );
- Return array_merge ($ x, array ($ k), $ y );
- } Else {
- Return $ arr;
- }
- }
- $ Test_array = array ();
- $ N = 0;
- // Test a 0.3 million record
- While (++ $ n <= 300000 ){
- $ Test_array [$ n] = $ n;
- }
- Echo 'Array init!
';
- Shuffle ($ test_array); // disrupt the order
- Echo 'Array shuffled
';
- Echo date ('Y-m-d H: m: s ').'
';
- $ Res = quickSort ($ test_array );
- Echo date ('Y-m-d H: m: s ');
- ?>
Fast sorting: 1). Divide the target array into two arrays. The first element is used as the benchmark by default. 2) if it is smaller than the reference object, it is allocated to the Left array; otherwise, it is allocated to the Right array; 3) According to this method, only one element exists in the array. |