Skip to content

Instantly share code, notes, and snippets.

@damdafayton
Last active June 18, 2022 06:39
Show Gist options
  • Save damdafayton/4b8a2d254cc84d3b8899bfdfc8d359fd to your computer and use it in GitHub Desktop.
Save damdafayton/4b8a2d254cc84d3b8899bfdfc8d359fd to your computer and use it in GitHub Desktop.
Simple quick sort - Ruby
# In Insertion sort, you simply went through each element in order and inserted it into a sorted sub-array. In this challenge, you cannot focus on one element at a time, but instead must deal with whole sub-arrays. Each time you call partition, you are sorting two parts of the array with respect to each other. Notice if you called partition on two elements, that sub-array would be fully sorted.
# Can you repeatedly call partition on each sub-array so that the entire array ends up sorted?
# In this challenge, print your array every time you finish your partitioning method, i.e. when you combine the partitioned array together. The first element in a sub-array should be used as a pivot. Partition the left side before partitioning the right side. Do not add the pivot to either side. Instead, put it in the middle when combining the two lists together.
def simple_quicksort(array)
# write your code here
# choose one > make two lists > loop the rest > if list bigger than 1 recurse > return all
pivot = array [0]
smaller_than_pivot, bigger_than_pivot = [], []
array.shift
array.each do |el|
if el<pivot then smaller_than_pivot.push(el)
else bigger_than_pivot.push(el)
end
end
smaller_than_pivot = simple_quicksort(smaller_than_pivot) if smaller_than_pivot.length>1
bigger_than_pivot = simple_quicksort(bigger_than_pivot) if bigger_than_pivot.length>1
result = [*smaller_than_pivot, pivot, *bigger_than_pivot]
puts result.join(' ')
return result
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment