Table of Contents
Basic idea :
Illustration:
Code:
Summary:
Home Backend Development PHP Tutorial [PHP Interview] An explanation of two simple sorting algorithms that must be asked in the interview: bubble sort and quick sort

[PHP Interview] An explanation of two simple sorting algorithms that must be asked in the interview: bubble sort and quick sort

Apr 17, 2019 pm 04:03 PM
php interview Bubble Sort Quick sort

Generally when facing interviews, we have no problem answering the interview questions. For PHP developers, in addition to being familiar with the projects they are doing, they also need to understand basic algorithms. Let’s share the algorithms that are often asked in PHP interviews: bubble sort and quick sort.

Bubble sorting: one-to-one comparison sorting

Basic idea:

Repeatedly visit the element sequence to be sorted , compare two adjacent elements in turn, and swap them if their order (such as from large to small) is wrong. The work of visiting elements is repeated until no adjacent elements need to be exchanged, which means that the elements have been sorted.

Illustration:

1. The first time: holding the first element of the array, Start comparing from the second element respectively. If the previous element is larger than the later element, swap the two elements to get the larger value. Continue the backward comparison until the end of the array element to achieve a bubbling (bubble Once, the maximum value of the current "remaining" array is obtained and placed at the "end" of the array)

2. Starting from the second time, the comparison still starts from the first element, but only the array is compared. The length should be -1 position, and the number of comparisons each time is -1

3. Repeat the comparison until finally there is no more numbers to compare

Code:

$arr = array(3,2,6,0,1,4,7);
        //因为排序需要每次将一个元素与数组的其他元素进行比较,所以需要两层循环来控制
        //外层循环控制冒泡次数
        //内存循环比较每次的大小,得到每次的最大值(泡)
 
        for($i = 0,$length = count($arr);$i < $length;$i++){
        
                 //内存循环
                 for($j = 0;$j < ($length - $i - 1);$j++){
                         //拿着j变量所对应的数组元素,与后面的元素进行比较
                         if($arr[$j] > $arr[$j + 1]){
                                  //交换位置
                                  $temp              = $arr[$j];
                                  $arr[$j]           = $arr[$j+1];
                                  $arr[$j+1]         = $temp;
                         }
                 }
        }
Copy after login

Summary:

The best time complexity of bubble sorting is O(n). Although it is not the optimal algorithm, it is something we often come into contact with and will also be asked in interviews. So we must understand the basic principles, be able to understand them, and be able to write them

Quick sort: Exchange space for time

Basic idea :

Divide the data to be sorted into two independent parts through one sorting. All the data in one part is smaller than all the data in the other part, and then use this method to separate the two parts of the data. Quick sort, the entire sorting process can be performed recursively, so that the entire data becomes an ordered sequence.

Illustration:

Find any element in the current array, as a standard, create two new empty arrays and traverse the entire array element, the traversed element is smaller than the current element, then put it in the array on the left; if it is larger, put it in another array

Recursive idea

1. Recursion point: If two If the elements of an array are greater than 1, they need to be decomposed again

2. Recursive exit: when the array element becomes 1

Code:

//待排序数组
        $arr = array(5,3,8,2,6,4,7);
        //函数实现快速排序
        function quick_sort($arr){
                 //判断参数是否是一个数组
                 if(!is_array($arr)) return false;
 
                 //递归出口:数组长度为1就直接返回数组
                 $length = count($arr);
                 if($length <= 1) return $arr;

                 //数组元素有多个
                 $left = $right = array();
                 //使用for循环进行遍历,把第一个元素当做比较的对象
                 for($i = 1;$i < $length;$i++){
                         //判断当前元素值的大小
                         if($arr[$i] < $arr[0]){
                                  //当前元素小于标准元素,放到左边数组
                                  $left[] = $arr[$i];
                         }else{
                                  $right[] = $arr[$i];
                         }
                 }
                 //递归调用
                 $left = quick_sort($left);
                 $right = quick_sort($right);
 
                 //将所有的结果合并
                 return array_merge($left,array($arr[0]),$right);
        }
Copy after login

Summary:

Quick sort is the fastest sorting method among general sorting methods. It is based on recursion and uses space for time. In general interviews, you will be asked to know the basic principles.

[Related tutorials: PHP video tutorial]

The above is the detailed content of [PHP Interview] An explanation of two simple sorting algorithms that must be asked in the interview: bubble sort and quick sort. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

Hot AI Tools

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.

Undress AI Tool

Undress AI Tool

Undress images for free

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Java data structures and algorithms: in-depth explanation Java data structures and algorithms: in-depth explanation May 08, 2024 pm 10:12 PM

Data structures and algorithms are the basis of Java development. This article deeply explores the key data structures (such as arrays, linked lists, trees, etc.) and algorithms (such as sorting, search, graph algorithms, etc.) in Java. These structures are illustrated through practical examples, including using arrays to store scores, linked lists to manage shopping lists, stacks to implement recursion, queues to synchronize threads, and trees and hash tables for fast search and authentication. Understanding these concepts allows you to write efficient and maintainable Java code.

How to implement bubble sort algorithm in C# How to implement bubble sort algorithm in C# Sep 19, 2023 am 11:10 AM

How to implement the bubble sort algorithm in C# Bubble sort is a simple but effective sorting algorithm that arranges an array by comparing adjacent elements multiple times and exchanging positions. In this article, we will introduce how to implement the bubble sort algorithm using C# language and provide specific code examples. First, let us understand the basic principles of bubble sort. The algorithm starts from the first element of the array and compares it with the next element. If the current element is larger than the next element, swap their positions; if the current element is smaller than the next element, keep it

Transform code with C++ function pointers: improve efficiency and reusability Transform code with C++ function pointers: improve efficiency and reusability Apr 29, 2024 pm 06:45 PM

Function pointer technology can improve code efficiency and reusability, specifically as follows: Improved efficiency: Using function pointers can reduce repeated code and optimize the calling process. Improve reusability: Function pointers allow the use of general functions to process different data, improving program reusability.

Java quick sorting tips and precautions Java quick sorting tips and precautions Feb 25, 2024 pm 10:24 PM

Master the key skills and precautions of Java quick sort. Quick sort (QuickSort) is a commonly used sorting algorithm. Its core idea is to divide the sequence to be sorted into two independent parts by selecting a benchmark element, and all the elements in one part are equal. is less than the base element, and all elements of the other part are greater than the base element, then the two parts are recursively sorted, and finally an ordered sequence is obtained. Although quick sort has a time complexity of O(nlogn) in the average case, it degenerates to O(nlogn) in the worst case

Guide to writing a custom sorting algorithm for PHP arrays Guide to writing a custom sorting algorithm for PHP arrays Apr 27, 2024 pm 06:12 PM

How to write a custom PHP array sorting algorithm? Bubble sort: Sorts an array by comparing and exchanging adjacent elements. Selection sort: Select the smallest or largest element each time and swap it with the current position. Insertion sort: Insert elements one by one into the sorted part.

How to implement quick sort using Python How to implement quick sort using Python Dec 18, 2023 pm 03:37 PM

How to implement quick sorting in Python: 1. Define a function called quick_sort and use the recursive method to implement quick sorting; 2. Check the length of the array. If the length is less than or equal to 1, return the array directly. Otherwise, select the array. The first element is used as the pivot element (pivot), and then the array is divided into two sub-arrays smaller than the pivot element and larger than the pivot element; 3. Connect the two sub-arrays and the pivot element to form a sorted array. .

Complexity analysis of various PHP array sorting algorithms Complexity analysis of various PHP array sorting algorithms Apr 27, 2024 am 09:03 AM

PHP array sorting algorithm complexity: Bubble sort: O(n^2) Quick sort: O(nlogn) (average) Merge sort: O(nlogn)

Analyze time complexity and space complexity in Go language Analyze time complexity and space complexity in Go language Mar 27, 2024 am 09:24 AM

Go is an increasingly popular programming language that is designed to be easy to write, easy to read, and easy to maintain, while also supporting advanced programming concepts. Time complexity and space complexity are important concepts in algorithm and data structure analysis. They measure the execution efficiency and memory size of a program. In this article, we will focus on analyzing the time complexity and space complexity in the Go language. Time Complexity Time complexity refers to the relationship between the execution time of an algorithm and the size of the problem. Time is usually expressed in Big O notation

See all articles