An in-depth analysis of quick sort in JavaScript
Introduction
Sorting refers to arranging the elements of a linear list in a specific order (numeric or alphabetical). Sorting is often used in conjunction with search.
There are many sorting algorithms, and one of the fastest by far is Quicksort(Quicksort).
Quicksort sorts the given list elements using the divide-and-conquer strategy. This means that the algorithm breaks the problem into subproblems until the subproblems become simple enough to be solved directly.
Algorithmically, this can be achieved using recursion or looping. But for this problem, it is more natural to use recursion.
Understand the logic behind quick sort
First look at how quick sort works:
- Select an element in the array, this element is called Benchmark(Pivot). Usually the first or last element in the array is used as the basis.
- Then, rearrange the elements of the array so that all elements to the left of the pivot are smaller than the pivot, and all elements to the right are greater than the pivot. This step is called Partitioning. If an element is equal to the base, it doesn't matter which side it is on.
- Repeat this process for the left and right sides of the benchmark until the array is sorted.
Next, understand these steps through an example. Suppose there is an array containing unsorted elements [7, -2, 4, 1, 6, 5, 0, -4, 2]
. Select the last element as the base. The decomposition steps of the array are shown in the figure below:
The elements selected as the basis in step 1 of the algorithm are colored. After partitioning, the base element is always at the correct position in the array.
The array with a bold black border represents what it will look like at the end of that particular recursive branch, with the resulting array containing only one element.
Finally you can see the sorting of the results of the algorithm.
Use JavaScript to implement quick sort
The backbone of this algorithm is the "partitioning" step. Whether using recursion or looping, this step is the same.
It is precisely because of this feature that the code for array partitioning is first written partition()
:
function partition(arr, start, end){ // 以最后一个元素为基准 const pivotValue = arr[end]; let pivotIndex = start; for (let i = start; i < end; i++) { if (arr[i] < pivotValue) { // 交换元素 [arr[i], arr[pivotIndex]] = [arr[pivotIndex], arr[i]]; // 移动到下一个元素 pivotIndex++; } } // 把基准值放在中间 [arr[pivotIndex], arr[end]] = [arr[end], arr[pivotIndex]] return pivotIndex; };
The code is based on the last element and uses the variable pivotIndex
to track the "middle" position where all elements to the left are smaller than pivotValue
and elements to the right are larger than pivotValue
.
The final step swaps the pivot (last element) with pivotIndex
.
Recursive implementation
After implementing the partition()
function, we must solve the problem recursively and apply partitioning logic to complete the remaining steps:
function quickSortRecursive(arr, start, end) { // 终止条件 if (start >= end) { return; } // 返回 pivotIndex let index = partition(arr, start, end); // 将相同的逻辑递归地用于左右子数组 quickSort(arr, start, index - 1); quickSort(arr, index + 1, end); }
In this function, the array is first partitioned, and then the left and right subarrays are partitioned. As long as this function receives an array that is not empty or has more than one element, the process will be repeated.
Empty arrays and arrays containing only one element are considered sorted.
Finally use the following example to test:
array = [7, -2, 4, 1, 6, 5, 0, -4, 2] quickSortRecursive(array, 0, array.length - 1) console.log(array)
Output:
-4,-2,0,1,2,4,5,6,7
Loop implementation
The recursive method of quick sort is more intuitive. But using loops to implement quick sort is a relatively common interview question.
Like most recursive to loop conversion solutions, the first thing that comes to mind is to use a stack to simulate recursive calls. Doing this allows you to reuse some familiar recursive logic and use it in loops.
We need a way to keep track of the remaining unsorted subarrays. One approach is to simply keep "pairs" of elements on the stack that represent the start
and end
of a given unsorted subarray.
JavaScript does not have an explicit stack data structure, but arrays support the push()
and pop()
functions. However, the peek()
function is not supported, so you must use stack [stack.length-1]
to manually check the top of the stack.
We will use the same "partitioning" function as the recursive method. Take a look at how to write the Quicksort part:
function quickSortIterative(arr) { // 用push()和pop()函数创建一个将作为栈使用的数组 stack = []; // 将整个初始数组做为“未排序的子数组” stack.push(0); stack.push(arr.length - 1); // 没有显式的peek()函数 // 只要存在未排序的子数组,就重复循环 while(stack[stack.length - 1] >= 0){ // 提取顶部未排序的子数组 end = stack.pop(); start = stack.pop(); pivotIndex = partition(arr, start, end); // 如果基准的左侧有未排序的元素, // 则将该子数组添加到栈中,以便稍后对其进行排序 if (pivotIndex - 1 > start){ stack.push(start); stack.push(pivotIndex - 1); } // 如果基准的右侧有未排序的元素, // 则将该子数组添加到栈中,以便稍后对其进行排序 if (pivotIndex + 1 < end){ stack.push(pivotIndex + 1); stack.push(end); } } }
Here is the test code:
ourArray = [7, -2, 4, 1, 6, 5, 0, -4, 2] quickSortIterative(ourArray) console.log(ourArray)
Output:
-4,-2,0,1,2,4,5,6,7
Visual demonstration
When it comes to sorting algorithms, Visualizing them can help us intuitively understand how they work. The following example is taken from Wikipedia:
The last element in the figure is also used as a benchmark. Given an array partitioned, recursively traverse the left side until it is completely sorted. Then sort the right side.
Efficiency of quick sort
Now discuss its time and space complexity. The worst-case time complexity of quick sort is $O(n^2)$. The average time complexity is $O(n\log n)$. Typically, worst-case scenarios can be avoided by using a randomized version of quicksort.
The weakness of the quicksort algorithm is the choice of benchmark. Each time you choose a wrong pivot (a pivot larger or smaller than most elements) you will get the worst possible time complexity. When repeatedly selecting a basis, if the element value is smaller or larger than the element's basis, the time complexity is $O(n\log n)$.
It can be observed from experience that no matter which data benchmark selection strategy is adopted, the time complexity of quick sort tends to have $O(n\log n)$.
Quicksort does not take up any additional space (excluding space reserved for recursive calls). This algorithm is called the in-place algorithm and requires no extra space.
For more programming-related knowledge, please visit: Introduction to Programming! !
The above is the detailed content of An in-depth analysis of quick sort in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Dreamweaver Mac version
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.
