Sorting: Selection Sort
Since I seem to be doing quite a few sorting algorithsms in my lectures at the moment, it would appear that I will be doing a series of sorting algorithm posts.
Today I did not have all that much time, so I wrote this one in javascript. I present to you: The selection sort.
The selection sort is a sorting algorithm where the smallest number is found and swapped with the number at the beginning, then the next smallest is swaped with the one next to the smallest number, and so on until the whoel sequence has been sorted.
Wikipedia has a rather nice animated GIF that explains the selection sort well here.
My implementation could be made faster be doing it in reverse, but I didn't have time to reverse it at the time of writing this post (check the comments to see if I did it later).
function selectionsort(arr)
{
var maxid = 0, temp;
for(var nextid = 0; nextid < arr.length - 1; nextid++)
{
//find the next smallest number remaining
maxid = nextid;
for(var j = nextid; j < arr.length; j++)
{
/*
Invert to |
sort desc.V */
if(arr[j] < arr[maxid])
maxid = j;
}
//swap the next number into place
arr[nextid] = arr.splice(maxid, 1, arr[nextid])[0];
console.log("nextid:", nextid, "state:", arr);
}
return arr; //for chaining
}
Here is a minified version (146 chars including newlines):
function selectionsort(e){for(var t=0,n=0;n<e.length-1;n++){t=n
for(var l=n;l<e.length;l++)e[l]<e[t]&&(t=l)
e[n]=e.splice(t,1,e[n])[0]}return e}
This was minified with UglifyJS.
Sample Output:
original [ 75, 4, 32, 87, 69, 73, 10, 18, 48, 2, 48, 96, 75, 36, 26 ]
nextid: 0 state: [ 2, 4, 32, 87, 69, 73, 10, 18, 48, 75, 48, 96, 75, 36, 26 ]
nextid: 1 state: [ 2, 4, 32, 87, 69, 73, 10, 18, 48, 75, 48, 96, 75, 36, 26 ]
nextid: 2 state: [ 2, 4, 10, 87, 69, 73, 32, 18, 48, 75, 48, 96, 75, 36, 26 ]
nextid: 3 state: [ 2, 4, 10, 18, 69, 73, 32, 87, 48, 75, 48, 96, 75, 36, 26 ]
nextid: 4 state: [ 2, 4, 10, 18, 26, 73, 32, 87, 48, 75, 48, 96, 75, 36, 69 ]
nextid: 5 state: [ 2, 4, 10, 18, 26, 32, 73, 87, 48, 75, 48, 96, 75, 36, 69 ]
nextid: 6 state: [ 2, 4, 10, 18, 26, 32, 36, 87, 48, 75, 48, 96, 75, 73, 69 ]
nextid: 7 state: [ 2, 4, 10, 18, 26, 32, 36, 48, 87, 75, 48, 96, 75, 73, 69 ]
nextid: 8 state: [ 2, 4, 10, 18, 26, 32, 36, 48, 48, 75, 87, 96, 75, 73, 69 ]
nextid: 9 state: [ 2, 4, 10, 18, 26, 32, 36, 48, 48, 69, 87, 96, 75, 73, 75 ]
nextid: 10 state: [ 2, 4, 10, 18, 26, 32, 36, 48, 48, 69, 73, 96, 75, 87, 75 ]
nextid: 11 state: [ 2, 4, 10, 18, 26, 32, 36, 48, 48, 69, 73, 75, 96, 87, 75 ]
nextid: 12 state: [ 2, 4, 10, 18, 26, 32, 36, 48, 48, 69, 73, 75, 75, 87, 96 ]
nextid: 13 state: [ 2, 4, 10, 18, 26, 32, 36, 48, 48, 69, 73, 75, 75, 87, 96 ]
result [ 2, 4, 10, 18, 26, 32, 36, 48, 48, 69, 73, 75, 75, 87, 96 ]
At some point I may port this to C♯.
(Probably) Coming Soon: (Binary) Insertion sort, Merge Sort, Quick Sort.