Pages

Saturday, December 25, 2010

Selection Sort Algorithm

/**
 * This framework provide a sorting service based on 
 * selection sort using Javascript.
 *
 * @author  : irfanudin ridho
 * @email   : irfan.ub@gmail.com
 * @date    : December 25, 2010
 * @version : 2.0
 */


/**
 * Constructor service
 * @param data Array of data
 */
function SelectionSort(data){
    this.data = data;
    this.len = this.data.length;
}


/**
 * method that provide ascending sorting services.
 * @return ascending order of array
 */
SelectionSort.prototype.getAsc = function(){
    for(i=0;i<this.len;i++){
        var minIndex = i;
        var tempValue = this.data[minIndex];
        for(j=i;j<this.len-1;j++){
            if(this.data[j+1]<this.data[minIndex]){
                minIndex = j+1;
            }
        }
        this.data[i] = this.data[minIndex];
        this.data[minIndex] = tempValue;
    }
    return this.data;
}


/**
 * method that give a service to give descending order
 * @return descending order of an array
 */
SelectionSort.prototype.getDesc = function(){
    for(i=0;i<this.len;i++){
        var maxIndex = i;
        var tempValue = this.data[maxIndex];
        for(j=i;j<this.len-1;j++){
            if(this.data[j+1]>this.data[maxIndex]){
                  maxIndex = j+1;
            }
        }
        this.data[i] = this.data[maxIndex];
        this.data[maxIndex] = tempValue;
    }
    return this.data;
}
       

No comments:

Post a Comment