Pages

Friday, December 24, 2010

JS - Selection Sort

/**
 * @author  : irfanudin ridho
 * @email   : irfan.ub@gmail.com
 * @date    : December 24, 2010
 * @version : 1.0
 */
/*
 * This function will do ascending sorting
 * 
 * @param data Array
 * @return Array ascending sorted array
 */

function ascSort(data){
    for(i=0;i<data.length;i++){
        var minPos = i;  // index of min value
        for(j=1;j<data.length-1;j++){
            if(data[j+1]<data[minPos]){
                minPos = j+1;
            }
        }
        var temp = data[i];
        data[i] = data[minPos];
        data[minPos] = temp;
    }
}



/*
 * This function will do descending sorting
 * 
 * @param data Array
 * @return Array descending sorted array
 */

function descSort(data){
    for(i=0;i<data.length;i++){
        var maxPos = i;  // index of max value
        for(j=1;j<data.length-1;j++){
            if(data[j+1]>data[maxPos]){
                maxPos = j+1;
            }
        }
        var temp = data[i];
        data[i] = data[maxPos];
        data[maxPos] = temp;
    }
}
          

No comments:

Post a Comment