Guest User

Recursive Bogosort

a guest
Jan 8th, 2014
171
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 1.48 KB | None | 0 0
  1. # Bogosort is kind of inefficient
  2. # Let's put a stop to all that.
  3.  
  4. def recursiveBogoSort(arr)
  5.    
  6.     if(arr.size > 3) then
  7.         a,b = goAheadAndSplit(arr)
  8.         return bogoSplice(recursiveBogoSort(a),recursiveBogoSort(b))
  9.     else
  10.        
  11.         until(isSorted(arr))
  12.             arr.shuffle!
  13.         end
  14.        
  15.         return arr
  16.        
  17.     end
  18.    
  19. end
  20.  
  21. # Takes two sorted arrays
  22. # Joins them into one sorted array
  23.  
  24. # If you pass unsorted arrays in, bad things will happen. Probably.
  25.  
  26. def bogoSplice(left,right)
  27.     l = "L" * left.size
  28.     r = "R" * right.size
  29.    
  30.     lr = (l+r).split("")
  31.    
  32.     puts left.join(",")
  33.     puts right.join(",")
  34.    
  35.     puts left.size + right.size
  36.    
  37.     # Need to initialise the combined array somehow
  38.     # lucky shot!
  39.    
  40.     spliced = (left + right).shuffle
  41.    
  42.     # prepare for poppery
  43.    
  44.     left.reverse!
  45.     right.reverse!
  46.    
  47.     until(isSorted(spliced))
  48.        
  49.         lleft = left.clone
  50.         rright = right.clone
  51.        
  52.         #puts "#"
  53.        
  54.         lr.shuffle!
  55.         spliced = []
  56.        
  57.         lr.each do |something|
  58.             if(something.eql?("L")) then
  59.                 spliced << lleft.pop
  60.             else
  61.                 spliced << rright.pop
  62.             end
  63.         end
  64.        
  65.         #puts spliced.join("-")
  66.         #print(".")
  67.        
  68.     end
  69.    
  70.     return spliced
  71.    
  72. end
  73.  
  74. # Array needs minimum size
  75. # Good thing we aren't calling it under that
  76.  
  77. def goAheadAndSplit(arr)
  78.    
  79.     x = arr.size / 2
  80.    
  81.     return arr[0..x-1] , arr[x..-1]
  82.    
  83. end
  84.  
  85. # Useful helper function
  86.  
  87. def isSorted(arr)
  88.     arr == arr.sort
  89. end
  90.  
  91. # sample usage
  92.  
  93. lol = []
  94.  
  95. 32.times do
  96.     lol << Random.rand(4125)
  97. end
  98.  
  99. puts recursiveBogoSort(lol).join(",")
Advertisement
Add Comment
Please, Sign In to add comment