Quicksort没有使用更小的阵列大小

时间:2014-11-09 08:13:47

标签: ruby algorithm sorting data-structures quicksort

下面是我在ruby中的快速排序代码,它的工作正常,对于20-25这样的数组大小,但是得到堆栈级别太深的错误或者它被卡住了更长的时间。

我猜我正在做一个微不足道的错误,但无法弄明白。

  # This program is to do sorting using Quick sort.
require 'colorize'

class QuickSort
 attr_accessor :array
  def initialize(size)
   puts "Generating Random numbers for your array".cyan
   @array = (1..size.to_i).map do 
    rand(500) # Generating random numbers between 1 to 500.
   end
  # Boundary case
   if @array.size == 1
    puts  "Your sorted array is"
    p @array
    return
   end
   puts "Array Before Sorting".yellow
   p @array
   @head = 0
   @tail = @array.size-1
   startSort(@array,@head,@tail) #Start the searching logic.
  end

 # Quicksort logic
 def startSort(array,head,tail)
  if head < tail
   pivot = partitionArray(array,head,tail) # Calling the sorting logic  
   startSort(array,head,pivot-1)
   startSort(array,pivot+1,@tail)
  end 
 end


 # This method is called to partition the array based on pivot.
 def partitionArray(array,head,tail)
  pivot_value = array[(head+tail)/2] # Choosing random pivot value.
 # Run this partition step until head is equal to tail
  while head <= tail
    if array[head] < pivot_value
     head += 1
    elsif array[head] >= pivot_value
     if array[tail] > pivot_value
      tail -= 1
     elsif array[tail] <= pivot_value
      # Swapping head and tail values
      temp = array[head]
      array[head] = array[tail]
      array[tail] = temp
      # Moving each pointer forward from both the directions.
      head += 1
      tail -= 1
     end     
    end     
   end
   return head # Nothing but pivot
 end
end


 puts "Enter the size of Array"
 @size = gets.chomp
 # Checking if entry is a valid integer or not.
 if @size.match(/^(\d)+$/) 
  @obj = QuickSort.new(@size)
  puts "Array after sorting is ".green
  p @obj.array
 else
  puts "Invalid Entry".red
 end

1 个答案:

答案 0 :(得分:1)

您的快速排序算法的实现不正确。在一行:
startSort(array, pivot + 1, @tail)
您始终为startSortpivot + 1调用array.size - 1方法,因为@tail是实例变量。它仅被分配给@array.size - 1一次,其值永远不会改变。但是,只需将此行更改为
startSort(array, pivot + 1, tail)
 不足以修复您的代码。通过此更改,即使对于大型阵列也可以快速工作,但会产生错误的答案。这条线实际上应该是:
startSort(array, pivot, tail)
 通过此更改,它可以快速处理大型数组并正确排序数组。