Skip to content

Instantly share code, notes, and snippets.

@harryworld
Last active August 29, 2015 14:10
Show Gist options
  • Save harryworld/7d038cc15af40fd89da0 to your computer and use it in GitHub Desktop.
Save harryworld/7d038cc15af40fd89da0 to your computer and use it in GitHub Desktop.
Sorting Algorithm

Sort the following sequence

[69,81,30,38,9,2,47,61,32,79]

Some common sorting algorithms

Selection Sort

It tries to find the smallest number and put it at the front.

def selectionsort(list)  
  list.size.times do |start|  
    min = start  
    start.upto(list.size-1) do |i|  
      min = i if list[i] < list[min]  
    end  
    list[start], list[min] = list[min], list[start]  
  end  
  list  
end 

Bubble Sort

It goes through the whole sequence, in order to compare the two elements next to each other. Biggest number would go to the end of sequence first.

  • Your time

Resources

@johnlok
Copy link

johnlok commented Nov 25, 2014


def bubble_sort(array)
  return array if array.size == 1
  swapped = true
  while swapped do #this will loop through the below block until everything has been swapped
    swapped = false
    0.upto(array.size - 2) do |i| # -2 because the last iteration would be for the last two elements
      if array[i+1] < array[i]
        array[i+1], array[i] = array[i], array[i+1]
        swapped = true
      end
    end
  end
  array
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment