Advertisement
oaktree

Quick Sort (Optimized + Insertion Sort) - Ruby

Mar 27th, 2016
163
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 1.54 KB | None | 0 0
  1. #! /usr/bin/env ruby
  2.  
  3. # str is array of chars
  4. # pivot point is index in array to pivot on
  5. # returns type like `str`
  6. #! /usr/bin/env ruby
  7. def sorted?(arr)
  8.     for i in 1...arr.length
  9.         return false if arr[i] < arr[i-1]
  10.     end
  11.  
  12.     return true
  13. end
  14.  
  15. def insertionsort(str)
  16.     strlen = str.length
  17.     while !sorted?(str)
  18.  
  19.         for i in 1...strlen #exclusive range
  20.  
  21.             if str[i-1] > str[i]
  22.                 hold = str[i] # store value to INSERT  
  23.  
  24.                 pos = i
  25.  
  26.                 while pos > 0 && str[pos - 1] > hold
  27.                     str[pos] = str[pos - 1] # shift up
  28.                     pos -= 1
  29.  
  30.                     # stop if we have shifted all the elements that are BOTH greater than str[i] AND
  31.                     # to the left of str[i]
  32.                 end
  33.                
  34.                 # put str[i] in its rightful spot, just left of the last element we shifted, or the original spot of
  35.                 # the last element we shifted
  36.                 str[pos] = hold
  37.             end
  38.  
  39.         end
  40.     end
  41.  
  42.     return str
  43. end
  44.  
  45. def quicksort(str, _begin, _end)
  46.     return str[_begin..._end] if _end - _begin <= 1
  47.    
  48.     if _end - _begin <= 10
  49.         return insertionsort(str[_begin..._end])
  50.     end
  51.          
  52.  
  53.     pivot = str[_end - 1] # choose last as pivot
  54.  
  55.     a = _begin
  56.     b = _end - 1
  57.  
  58.     while (b > a)
  59.         if str[b-1] > pivot
  60.             str[b] = str[b-1]
  61.             b-=1
  62.         else
  63.             str[b-1],str[a] = str[a],str[b-1]
  64.             a+=1
  65.         end
  66.     end
  67.  
  68.     str[b] = pivot
  69.  
  70.     str[ _begin...b ] = quicksort(str, _begin, b) if b - _begin > 1
  71.     str[ (b+1)..._end] = quicksort(str, b+1, _end) if _end - b > 1
  72.  
  73.     return str[_begin..._end]
  74.  
  75. end
  76.  
  77. puts "give me a string"
  78. str = gets.chomp.split('')
  79.  
  80. puts quicksort(str, 0, str.length).join('')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement