Ruby selection sort.
The general idea behind selection sort is, finding the least element in an array and exchanging it with the item in the first position of that given array. Two loops are used. The outer one shows where we are in the array and the second finds the smallest element between the current array item and the last item. Any time the smallest element is found its exchanged with the outer loops current variable. By the end every execution of an inner loop the items to the left are sorted in order leaving the right side unsorted.
1 a = [ 5,2,1,7,4,3]
2 (a.size-1).times do |i| #produces the indexes of the array elements
3 min = i #the current item is concidered or assumed to be the smallest
4 (i+1).upto(a.size-1) do |j| #scan from a[j+1 ... size-1]
5 if a[j] < a[min]
6 min = j #update new minimum value
7 end
8 end
9 temp = a[i] #the code below is to swap the
10 a[i] = a[min] #elements.
11 a[min] = temp
12 end
13 puts a
About this entry
You’re currently reading “Ruby selection sort.,” an entry on Connecting the dots
- Published:
- 3.24.08 / 9am
- Category:
- Programming
1 Comment
Jump to comment form | comments rss [?] | trackback uri [?]