A Beginner's Guide to Understanding and Implementing Quick Sort Algorithm with JavaScript Example.
The quick sort algorithm is a divide-and-conquer algorithm that is used to sort an array of elements. The basic idea behind quick sort is to partition the array into two smaller sub-arrays, one containing elements that are less than the pivot element and the other containing elements that are greater than or equal to the pivot element. The pivot element is typically chosen as the last element in the array, but it can also be chosen randomly or as the median of the array.
In the example provided, the quickSort() function takes an array as input and checks if the length of the array is less than or equal to 1. If the length of the array is less than or equal to 1, the function returns the array as it is already sorted. If the length of the array is greater than 1, the function proceeds to partition the array.
The pivot element is chosen as the last element in the array, which is 6 in this example. The function then initializes two empty arrays called left and right. A for loop iterates through the array and compares each element to the pivot element. Elements that are less than the pivot element are added to the left array and elements that are greater than or equal to the pivot element are added to the right array.
After partitioning the array, the function recursively calls itself on the left and right arrays. The function is called on the left array first, sorting the elements less than the pivot element. Then, it is called on the right array, sorting the elements greater than or equal to the pivot element.
The function then concatenates the sorted left array, pivot element and sorted right array, to return a fully sorted array.
Here is an example of a quick sort algorithm implemented in JavaScript:
function quickSort(arr) {
if (arr.length <= 1) {
return arr;
}
let pivot = arr[arr.length - 1];
let left = [];
let right = [];
for (let i = 0; i < arr.length - 1; i++) {
if (arr[i] < pivot) {
left.push(arr[i]);
}
else
{
right.push(arr[i]);
}
}
return [...quickSort(left), pivot, ...quickSort(right)];
}
let arr = [5, 2, 9, 1, 5, 6];
console.log(quickSort(arr));
// Output: [1, 2, 5, 5, 6, 9]
In the above example, the pivot element is the last element in the array (6). The for loop iterates through the array and compares each element to the pivot element. Elements that are less than the pivot element are added to the left array, and elements that are greater than or equal to the pivot element are added to the right array. The function then recursively calls itself on the left and right arrays until the base case of an array with a length of 1 or less is reached.
Please note that this implementation of quick sort is not efficient and it is not recommended to use it in production.
Comments
Post a Comment