Computer Science‎ > ‎

Basic Data Structures in Ruby - Selection Sort



Programming With Ruby

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



Programming With Ruby

 Introduction to Ruby and some playing around with the Interactive Ruby Shell (irb)

Introduction to Ruby - Conditional statements and Modifiers: If-then, Unless, Case

Introduction to Ruby Comments - Single and Multi-Line comments

Introduction to Ruby Loops - Using While, Until, For, Break, Next , Redo, Retry

Introduction to Ruby - Arrays - Sorting, Filtering (Select), Transforming, Multi-Dimensional Arrays 

Introduction to Ruby - Strings

Introduction to Ruby - Making a Script Executable

Introduction to Ruby - Regular Expressions, Match, Scan

Introduction to Ruby - Computing Factorials Recursively : An Example of Recursion

Introduction to Ruby - Binomial Coefficients (nCr) : An Example of Recursion

Introduction to Ruby - Computing a Power Set : An Example of Recursion

Introduction to Ruby - Towers of Hanoi : An Example of Recursion

 Introduction to Ruby - Strings: Substitution, Encoding, Built-In Methods

Basic Data Structures in Ruby - Insertion Sort

Basic Data Structures in Ruby - Selection Sort

Basic Data Structures in Ruby - Merge Sort

Basic Data Structures in Ruby - Quick Sort

Functional Programming with Ruby

Basic Data Structures in Ruby - Stack

Basic Data Structures in Ruby - The Queue

Basic Data Structures in Ruby - Linked List - ( A Simple, Singly Linked List)

Basic Data Structures in Ruby - Binary Search Tree