search
HomeBackend DevelopmentPHP TutorialImplementation of PHP Cocktail sorting algorithm (code example)

Cocktail sort is also called bidirectional bubble sort, shaker sort, ripple sort, shuffle sort or shuttle sort. A variant of bubble sort, it is both a stable sorting algorithm and a comparison sort.

Implementation of PHP Cocktail sorting algorithm (code example)

This algorithm differs from bubble sort in that it sorts in both directions each time it traverses the list. This sorting algorithm is actually more difficult to implement than bubble sort, and solves the turtle problem in bubble sort. It only provides minor performance improvements and does not improve asymptotic performance; like bubbles, while it is useful in education, it has no practical significance.

An example of cocktail sorting visualization animation is as follows:

Implementation of PHP Cocktail sorting algorithm (code example)

##An example of PHP cocktail sorting code is as follows:

<?php
function cocktailSort($my_array)
{
    if (is_string($my_array))
        $my_array = str_split(preg_replace(&#39;/\s+/&#39;,&#39;&#39;,$my_array));

    do{
        $swapped = false;
        for($i=0;$i<count($my_array);$i++){
            if(isset($my_array[$i+1])){
                if($my_array[$i] > $my_array[$i+1]){
                    list($my_array[$i], $my_array[$i+1]) = array($my_array[$i+1], $my_array[$i]);
                    $swapped = true;
                }
            }
        }

        if ($swapped == false) break;

        $swapped = false;
        for($i=count($my_array)-1;$i>=0;$i--){
            if(isset($my_array[$i-1])){
                if($my_array[$i] < $my_array[$i-1]) {
                    list($my_array[$i],$my_array[$i-1]) = array($my_array[$i-1],$my_array[$i]);
                    $swapped = true;
                }
            }
        }
    }while($swapped);

    return $my_array;
}
$test_array = array(3, 0, 2, 5, -1, 4, 1);
echo "原始数组:\n";
echo implode(&#39;, &#39;,$test_array );
echo "\n排序后数组\n:";
echo implode(&#39;, &#39;,cocktailSort($test_array)). PHP_EOL;

Output:


原始数组: 3, 0, 2, 5, -1, 4, 1
排序后数组 :-1, 0, 1, 2, 3, 4, 5

This article is about the implementation method of PHP Cocktail (Cocktail) sorting algorithm. I hope it will be helpful to friends in need!

The above is the detailed content of Implementation of PHP Cocktail sorting algorithm (code example). For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Modern PHP: Leveraging Destructuring and the Spread Operator with Indexed ArraysModern PHP: Leveraging Destructuring and the Spread Operator with Indexed ArraysAug 08, 2025 pm 06:39 PM

PHP supports array deconstruction using the [] syntax since version 7.1, which can directly assign the value of the indexed array to variables; 2. Use the... operator to implement array expansion (similar to JavaScript's extension operator), which is used to merge arrays or transfer function parameters; 3. It can capture remaining elements with... operators, and simulate rest parameters; 4. Actual applications include processing CSV rows, function return value deconstruction and configuration merging; 5. Note... only applicable to index arrays, associative arrays should be used or array_merge(), and it does not support deep nested deconstruction of a single row, and needs to be processed in steps. Although modern PHP does not have the exact same deconstruction and extension syntax for JS, similar effects can be achieved through [] and...

Graceful Degradation: Handling Missing and Malformed $_GET Parameters in PHPGraceful Degradation: Handling Missing and Malformed $_GET Parameters in PHPAug 08, 2025 pm 06:38 PM

To effectively handle missing or malformed $_GET parameters in PHP, input must be validated and cleaned first, provided default values, accessed data using type-safe methods, and failed gracefully in a user-friendly way. 1. Always check whether the parameters exist and verify their type and format, such as using isset() and filter_input() to ensure that the id is a positive integer; 2. Set safe default values for optional parameters, such as paging or sorting fields to avoid crashes due to missing; 3. Avoid direct access to $_GET, safe reading should be performed by encapsulating functions such as get_param() and get_int() combined with null merge operators; 4. When the parameters are invalid, the API should return 400 status code and JSON errors

From Validation to Transformation: A Guide to `preg_filter`From Validation to Transformation: A Guide to `preg_filter`Aug 08, 2025 pm 06:37 PM

preg_filter only returns replacement results when matched, otherwise it returns null, suitable for scenarios where verification and conversion are required; 1. The main difference between it and preg_replace is that it returns null instead of the original string when mismatch; 2. It is suitable for only retaining and converting data that conforms to the pattern; 3. When processing arrays, it automatically filters mismatch elements but retains key names, and can be reindexed with array_values; 4. Supports backreferences and moderate performance, suitable for form processing, URL rewriting and other scenarios; 5. When you need to keep all inputs, you should use preg_replace, while in the scenario of verification and conversion, preg_filter is more efficient and concise.

Mastering RESTful Services with $_SERVER['REQUEST_METHOD']Mastering RESTful Services with $_SERVER['REQUEST_METHOD']Aug 08, 2025 pm 06:36 PM

$_SERVER['REQUEST_METHOD'] is the core tool used in PHP to build RESTful APIs. It routes processing logic by judging HTTP request methods (such as GET, POST, PUT, DELETE). 1. Use the switch statement to perform corresponding operations based on the value of $_SERVER['REQUEST_METHOD']; 2. For PUT and DELETE requests, the input data needs to be manually parsed through file_get_contents('php://input'), because $_POST is not applicable; 3. Build a single entry point (such as index.php) to implement REST routing, supporting different parties

The Perils of Unchecked Input: Preventing SQL Injection from Tainted $_POST DataThe Perils of Unchecked Input: Preventing SQL Injection from Tainted $_POST DataAug 08, 2025 pm 06:35 PM

AlwaysusepreparedstatementswithparameterizedqueriestopreventSQLinjectionwhenhandling$_POSTdata.2.Validateandsanitizeinputearlybycheckingforrequiredfields,filteringdata,trimminglength,andrejectingunexpectedcharacters.3.Avoidrelyingonmysqli_real_escape

The $_REQUEST Superglobal: A Convenience That Costs You Control and SecurityThe $_REQUEST Superglobal: A Convenience That Costs You Control and SecurityAug 08, 2025 pm 06:34 PM

Using $_REQUEST will cause the order of input sources to be uncontrollable, which may cause conflicts between POST and GET parameters or be maliciously overwritten; 2. Due to the contain COOKIE data, attackers can perform security attacks such as privilege escalation by forging cookies; 3. It is easy for developers to ignore input verification sources, reducing code traceability and security; $_GET, $_POST or $_COOKIE should always be used to clearly specify the input source to improve the predictability, debugging and security of the code. If necessary, $_REQUEST can be disabled by configuring variables_order or request_order.

A Modern Approach to Sanitization: Using `filter_input` with INPUT_POSTA Modern Approach to Sanitization: Using `filter_input` with INPUT_POSTAug 08, 2025 pm 06:33 PM

Use filter_input function to process POST input in PHP, because it can simultaneously implement secure access and filter verification, avoiding the risks of XSS and SQL injection caused by direct use of $_POST; 1. Use FILTER_SANITIZE_FULL_SPECIAL_CHARS to replace the deprecated FILTER_SANITIZE_STRING for special character escape; 2. Use FILTER_VALIDATE_EMAIL and FILTER_VALIDATE_INT to ensure the correct data format; 3. Arrays or multiple fields can be batch processed through encapsulation functions; 4. Pay attention to starting from PHP8.1

Refactoring Complex Nested Loops for Readability and MaintainabilityRefactoring Complex Nested Loops for Readability and MaintainabilityAug 08, 2025 pm 06:32 PM

Extract nested logic to independent functions to reduce complexity and improve readability; 2. Use list comprehensions or generator expressions when applicable to make the code concise; 3. Flatten the data structure through iterative tools or data preprocessing to reduce nesting; 4. Use built-in library functions such as itertools to optimize loop structures; 5. Consider object-oriented or functional programming mode to encapsulate repetitive logic; the ultimate goal is to make the code intention clear through clear abstraction and naming, avoid understanding difficulties caused by deep nesting, thereby improving maintainability and readability.

See all articles

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools