Data Structure and Algorithm
This article is part of series in Data Structure and Algorithm:
In this tutorial, we will learn a simple sorting algorithm - Quick Sort.
Table Of Content
1. Problem to Solve
Given a list of numbers as shown below, please sort them in ascending order.
- You are required to use Quick Sort algorithm when sorting the numbers.
- You are required to implement the algorithm in PHP language.
Quick Sort is also a divide and conquer algorithm, similar to Merge Sort. It works by choosing an element(pivot) from the list and placing elements that are less than the pivot on its left side and elements that are greater than the pivot on its right side. We repeat the steps for both left side and right side until the list can no longer be divided.
Choosing a pivot can be tricky, normally we just use the first or the last element.
Pseudocode of Quick Sort algorithm can be written as follows:
3. PHP Implementation
As we can see, we are using recursion for this algorithm. Typically, a divide and conquer algorithm implies the algorithm can be written recursively.
Quick Sort is indeed very simple to implement as a divide and conquer algorithm.
4. The End
If you like our post, please follow us on Twitter
and help spread the word. We need your support to continue.
If you have questions or find our mistakes in above tutorial, do leave a comment below to let us know.