Quick Sort using Javascript

WBOY
Release: 2024-08-17 20:47:32
Original
233 people have browsed it

Quick Sort using Javascript

Implementing Quick Sort is bit tricky but if you understand it and keep on practice it will be easier.

const quickSort = (arr, lo, hi) => { if (lo >= hi) { return ; } const pivotIndex = getPivotIndex(arr, lo, hi); quickSort(arr, lo, pivotIndex-1); quickSort(arr, pivotIndex+1, hi); } const getPivotIndex = (arr, lo, hi) => { const pivot = arr[hi]; let idx = lo-1; for (let i = lo; i< hi; i++) { if (arr[i] <= pivot) { idx++; const temp = arr[i]; arr[i] = arr[idx]; arr[idx] = temp; } } idx++; const temp = arr[idx]; arr[idx] = pivot; arr[hi] = temp; return idx; } const arr = [9,1,0,3,2,5,9,10, 11]; quickSort(arr, 0, 8); console.log(arr); // [0, 1, 2, 3, 5, 9, 9, 10, 11]
Copy after login

Try to dry run it you will get the clear picture.

The above is the detailed content of Quick Sort using Javascript. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!