Advertisement
Guest User

custom_sort

a guest
Feb 13th, 2014
167
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.78 KB | None | 0 0
  1. def sort(arr)
  2. rec_sort(arr, [])
  3. end
  4.  
  5. #define a sort method that takes an array as a parameter
  6. #inside the sort method, have it call a recursive sort method that takes
  7. # two parameters to be defined later
  8.  
  9. def rec_sort(unsorted, sorted)
  10. if unsorted.length <= 0
  11. return sorted
  12. end
  13.  
  14. #rec_sort method takes an unsorted array and a sorted array
  15. #checks to see if the unsorted array is equal to or less than 0
  16. #essentially checking if it is empty
  17. #if it is empty, then just return the sorted array
  18.  
  19. #if it is not empty, there is more work to be done
  20. smallest = unsorted.pop
  21. still_unsorted = []
  22. #sets a variable smallest equal to the last element of the unsorted array
  23. #also removes that element from the unsorted array
  24. #initializes an empty array called still_unsorted
  25.  
  26. unsorted.each do |tested_object|
  27. if tested_object < smallest
  28. still_unsorted.push(smallest)
  29. smallest = tested_object
  30. else
  31. still_unsorted.push(tested_object)
  32. end
  33. end
  34.  
  35. #after we've established that the unsorted array is not empty, we are going to iterate through it to add words to the sorted array
  36. #going through the unsorted array, we call each element tested_object
  37. #if tested_object is less than (lexigcoraphically) smallest, we push smallest to the still_unsorted array, and we make smallest equal to tested_object
  38. #if tested_object > smallest, then we push tested_object into the still_unsorted array
  39. #this is creating the still_unsorted array
  40.  
  41. #now 'smallest' really does point to the smallest element that 'unsorted' contained, and all the rest of it is in still_unsorted
  42. sorted.push(smallest)
  43. #push smallest into the sorted array
  44.  
  45. rec_sort(still_unsorted, sorted)
  46. end
  47.  
  48. puts(sort(['can', 'feel', 'singing', 'like', 'a', 'can']))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement