💻 Developer by day, 🎮 gamer by night | Software Engineer in @Taboola | ☕ sometimes coffee lover | A good player in call of duty | 📷 sometimes love photography
Quicksort algorithm is a “divide and conquer” algorithm. It takes the “pivot” element from the array and partitioning the other element into sub-arrays.
We can select the pivot with many ways but here I am going to select the last element with my example.
In case you want to understand what “divide and conquer” mean here:
As you can see in screenshot above, it is partitioning the arrays we will be using the same approach here with go to create this algorithm.
Let’s assume we have the following arrays:
Here is our approach how we are going to create our pseudo code with the following way:
Pseudo code for our recursive algorithm:
Let’s create a quick program using golang to show how we’re implementing this Pseudo code.
Firstly let’s create a simple logic with arrays:
As you can see, we just created a simple logic to make sure we are good at printing, now let’s implement quick sort function with our main program:
Let’s have a quick look at quicksort function logic
Let’s create a logic for our partitioning function
Notice here two things which I made a mistake when I was implementing the logic:
Inside partition function, our loop starts with low since our quicksort function is recursive. So we don’t wanna mess up with arrays index here.
Swapping, since go returns multiple return value so swapping is much easier with go. We don’t need to define a separate function or temp declaration.
Hopefully, we should get the following output:
In case, you want to see the complete program so here it is:
Time complexity
Worst Time Complexity : O(n^2)
Worst case can happen when array is already sorted
Best time complexity : O(nlogn)
Average Time Complexity : O(nlogn)
Implemeting receiver function
Let’s try some way in go using receiver function, as we know that go has some receiver functional way. So, let’s modify our function and implment some receiver way.
We need to declare first the type here:
After adding the type, we can declare our function something like with receiver function:
As you can see here, we have called our function using receiver quicksortAlgo.quicksort(arr, low, high). Also we are printing the array value from the receiver function quicksortAlgo.printArray(arr)
Alright, talk is enough. Let me show you the full code ;)
Your feedback is appreciated, please feel free to reach out to me on @rajendraarora16 for any suggestions.
Would be happy to say 👋