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

Posted

tags:

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

#Selection Sort


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

# Selection Sort *************************
# Selection Sort -> A popular quadratic sorting algorithm with O(n^2) complexity
# For Index [i] -> swap the i-th smallest element from (array[i]....array[length-1]) with array[i-1]  
def selectionSort(arr)
    for index in 0..(arr.length-1)
        temp = arr[index]
        min = temp
        indexToSwap = index
        for selectedIndex in (index+1)..(arr.length-1)
            if arr[selectedIndex] < min
                min = arr[selectedIndex] 
                indexToSwap = selectedIndex
            end
        end 
        arr[indexToSwap] = temp
        arr[index] = min    
    end
end


original_array=[2,19,5,4,3,14,2]
puts "Sorted Array Using Selection Sort:"
selectionSort(original_array)
p original_array

=begin
Output ****
Sorted Array Using Selection Sort:
[2, 2, 3, 4, 5, 14, 19]
=end

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

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

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

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

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

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

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