ruby Ruby的算法和数据结构 - #3快速排序

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ruby Ruby的算法和数据结构 - #3快速排序相关的知识,希望对你有一定的参考价值。




#The Quick Sort is a popular sorting algorithm, which has been discussed in detail, with examples and C code over here : Arrays and Sorting: Quick Sort ( with C Program source code). In this tutorial, we will take a quick look at the ruby implementation of Quick Sort.

#1

def partition arr, lo, hi  
  i,j = lo+1,hi
  while true
    i+=1 while arr[i] <= arr[lo] and i < hi
    j-=1 while arr[j] > arr[lo] and j > lo
    break if i>=j
    arr[i], arr[j] = arr[j], arr[i] #swap
  end
  arr[lo], arr[j] = arr[j], arr[lo]
  j
end

def quicksort arr, lo = 0, hi = nil  
  hi ||= arr.size - 1
  return arr if hi <= lo
  pivot = partition arr, lo, hi
  quicksort arr, lo, pivot-1
  quicksort arr, pivot+1, hi
end

#test
p quicksort [3,4,2,6,56,14,33,1,9,6] #[1, 2, 3, 4, 6, 6, 9, 14, 33, 56]

#2
def quickSort(arr,from,to)
    return if from >= to    
    pivot = arr[from]
    i = from
    for j in (1+from)..to
        if arr[j] < pivot
            i = i + 1
            temp = arr[i]
            arr[i] = arr[j]
            arr[j] = temp
        end 
    end
    quickSort(arr,from,i-1);
    quickSort(arr,i+1,to);
end


original_array=[2,19,5,4,3,14,2]
puts "Sorted Array Using Quick Sort:"
quickSort(original_array,0,original_array.length - 1)
p original_array

以上是关于ruby Ruby的算法和数据结构 - #3快速排序的主要内容,如果未能解决你的问题,请参考以下文章

ruby Ruby的算法和数据结构 - #6队列

ruby Ruby的算法和数据结构 - #8二叉树

ruby Ruby的算法和数据结构 - #7 LinkedList

ruby Ruby的算法和数据结构 - #5 Stack

ruby Ruby的算法和数据结构 - #2选择排序

ruby Ruby的算法和数据结构 - #1插入排序