Selection Sort

Sorting an array by first searching the minimum of the array , then adding it to a new array , recursively , for n-1 elements.

by dreiv

JavaScript

function printArray(elements) {
    for (var index = 0; index < elements.length; index++) {
        document.write(elements[index] + " ");
    }
    document.write("<br>");
}

function selectionSort(elements)
{
    document.write("<p>This is Selection Sort for a given array:</p>")
    var replaceIndex = 0;
    for(var index = 0; index < elements.length - 1 ; index++)
    {
        var min = elements[index];
        for(var j = index + 1; j < elements.length; j++)
        {
            if(min > elements[j])
            {
                min = elements[j];
                replaceIndex = j;
            }
        }
        elements[replaceIndex]=elements[index];
        elements[index] = min;
        printArray(elements);
    }
}

var elem = [31, 41, 59, 26, 41, 58];
selectionSort(elem);