Understanding quick sort

Quick sort is another efficient sorting algorithm that applies the divide-and-conquer method. Although it does not divide into equal halves like merge sort, it creates dynamic partitions to sort the data. This is how quick sort works:

  1. Pick a random value from the array, which we will call pivot.
  2. Reorder the array so that the item that is smaller than the pivot goes to the left of it, and the items that are greater than, or equal to, the pivot go to the right of it. This is known as partitioning.
  3. Recursively call steps 1 and 2 to solve the two subarrays (left and right of pivot) until all items are sorted.

There are many ways to picking a pivot from the array. We can either choose the left-most item of the array or the right-most item of the array. In both cases, if the array is already sorted, it will take worst case complexity. Choosing a good pivot can improve the efficiency of the algorithm. There are some different ways of doing a partition. We will explain the Hoare Partition, which makes comparatively fewer swaps than other partition methods. Here is our pseudo algorithm for the quick sort. We will do in-place sorting so that no extra space is required:

procedure Quicksort(A : array,p :int ,r: int)
if (p < r)
q = Partition(A,p,r)
Quicksort(A,p,q)
Quicksort(A,q+1,r)
end if
end procedure

procedure Partition(A : array,p :int ,r: int)
pivot = A[p]
i = p-1
j = r+1
while (true)
do
i := i + 1
while A[i] < pivot
do
j := j - 1
while A[j] > pivot

if i < j then
swap A[i] with A[j]
else
return j
end if
end while
end procedure

We used the first item as the pivot element. We can also choose the last item or take a median for choosing the pivot element. Let's now implement the algorithm using PHP.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset