Skip to content

Instantly share code, notes, and snippets.

@jtpaasch
Created July 24, 2013 12:16
Show Gist options
  • Save jtpaasch/6070001 to your computer and use it in GitHub Desktop.
Save jtpaasch/6070001 to your computer and use it in GitHub Desktop.
A simple implementation of the quick sort algorithm.
#!/bin/bash
# A basic quick sort implementation.
# It takes a list of numbers (separated by spaces),
# and it prints them out in ascending order.
quicksort() {
# The list passed in.
local LIST=($@)
# What's the length?
local LENGTH=${#LIST[@]}
# What's the middle number?
local PIVOT=${LIST[$(( $LENGTH / 2 ))]}
# Values in the list that are lesser than the pivot will go here:
local LESSER=()
# Values in the list that are greater than the pivot will go here:
local GREATER=()
# Values in the list that are equal to the pivot will go here:
local EQUAL=()
# If we have more than one item in the list,
# we can process it.
if [[ $LENGTH -gt 1 ]]; then
# Sort each item in the list into
# $LESSER, $GREATER, and $EQUAL lists.
for N in ${LIST[@]}
do
if [[ $N -lt $PIVOT ]]; then
LESSER=( ${LESSER[@]} $N )
elif [[ $N -gt $PIVOT ]]; then
GREATER=( ${GREATER[@]} $N )
else
EQUAL=( ${EQUAL[@]} $N )
fi
done
# Now sort each sub-list (if it has any members in it).
if [[ ${#LESSER[@]} -gt 0 ]]; then
quicksort ${LESSER[@]}
fi
if [[ ${#EQUAL[@]} -gt 0 ]]; then
quicksort ${EQUAL[@]}
fi
if [[ ${#GREATER[@]} -gt 0 ]]; then
quicksort ${GREATER[@]}
fi
# If there's just one item in the list, we can print it.
else
printf "${LIST[@]} "
fi
}
# Example.
# Here's an unsorted list
LIST="10 2 5 3 6 7 0 4 8 13"
# Sort it with quicksort, and store the output in $SORTED_LIST
SORTED_LIST=`quicksort ${LIST[@]}`
# Print 'er out.
echo $SORTED_LIST
exit 0
@drizzt
Copy link

drizzt commented Feb 19, 2014

Simple and broken, if you have a duplicated element in the list it will loop forever

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment