Search This Blog

2023/04/18

Javascript Algorithm :Quick Sort

function quicksort(arr) {

if (arr.length <= 1) {
return arr
} else {
var pivot = arr[0]
var left = []
var right = []

for (var i = 1; i < arr.length; i++) {
if (arr[i] < pivot) {
left.push(arr[i])
} else {
right.push(arr[i])
}
}
return quicksort(left).concat(pivot, quicksort(right))
}
}


var array = [10, 5, 2, 3, 7, 6, 8, 9, 1, 4];
var sortedArray = quicksort(array);
console.log(sortedArray);



The worst-case time complexity of QuickSort is O(n^2),
which occurs when the pivot selection is such that the
algorithm partitions the array into two sub-arrays of very
different sizes. This can happen, for example, when the input
array is already sorted or nearly sorted.

However, on average, QuickSort has a time complexity of O(n log n),
which is faster than many other sorting algorithms.
This average case time complexity is based on the assumption
that the pivot selection is done randomly or using a
-of-three pivot selection strategy.

The space complexity of QuickSort is O(log n) due to the recursion stack,
where n is the number of elements in the input array. However,
this space requirement can be reduced to O(1) if an in-place partitioning algorithm is used.

No comments:

Post a Comment