Created
July 24, 2013 12:16
-
-
Save jtpaasch/6070001 to your computer and use it in GitHub Desktop.
A simple implementation of the quick sort algorithm.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Simple and broken, if you have a duplicated element in the list it will loop forever