An online markdown blog and knowledge repository.
Page dedicated to storing randome notes and thoughts about various data structures and algorithms.
Goal is to have a reference to path experiences with DSAs.
This kept me busy for a long time. Several attempts to solve this without looking directly at a solution were difficult experiences. There were times when I got close, and a few common issues would crop up:
I used the following references to get started with Quicksort:
Wikipedia: The article does a fair job of describing Quicksort and even has a neat animation supporting the descriptive text.
Essential Algorithms [Stephens, Rod]: The text does a fair job of describing Quicksort, but the pseudocode is actually mixed text and pseudocode which caused some confusion for me. Stephens reviews several approaches to finding a 'pivot'. He also discusses two methods to managing item swapping/replacement: Using Stacks or Recursion.
Java:
public class StephensQuicksort {
public static void quicksort(int[] inputArr){
if (inputArr.length < 2) {
return;
}
int leftIdx = 0;
int rightIdx = inptuArr.length - 1;
quickSorter(leftIdx, rightIdx, inputArr);
return;
}
public static void quickSorter(int start, int end, int[] numberArray){
if (start >= end){
return;
}
int divider = numberArray[start];
int lo = start;
int hi = end;
boolean outerContinue = true;
// find a value lower than divider and store its index
while (true && outerContinue) {
hi--;
if (hi <= lo) {
keepGoing = false;
}
}
// if index of higher value has crossed the other index
// place divider at that index but keep the hi index
if (hi <= lo) {
numberArray[lo] = divider;
outerContinue = false;
break;
}
// swap value at lower index with one in higher index
// and move the index pointer forward for more testing
numberArray[lo] = numberArray[hi];
lo++;
keepGoing = true;
// find a value higher than divider and store its index
while (numberArray[lo] < divider && keepGoing) {
lo++;
if (lo >= hi) {
keepGoing = false;
break;
}
}
keepGoing = true;
// reset lower index to higher index value and set
// divider to higher index if the indices have crossed
if (lo >= hi && outerContinue) {
lo = hi;
numberArray[hi] = divider;
outerContinue = false;
break;
}
// reassign array at hi index with
// value from array at low index
numberArray[hi] = numberArray[lo];
}
// partition: only send array element from start
// to wherever low index is now (exclusive)
quickSorter(start, lo - 1, numberArray);
// only send array elements above through end of
// array to the recursive call for next sort run
quickSorter(lo + 1, end, numberArray);
// if code reaches this point this function get removed from
// the stack and calling function continues where it left off
return;
}
Wikipedia Quicksort
Essential Algorithms: A Practical Approach to Computer Algorithms [Essential Algorithms, Stephen, Rod. Published 2013, Wiley and Sons]
Return to Conted Index
Return to Root README