Pages

Friday, December 24, 2010

JS - Find And Replace

/**
 * Find And Replace Algorithm
 *
 * @author   irfanudin ridho
 * @email    irfan.ub@gmail.com
 * @date     December 24, 2010
 * @version  1.0
 * 
 */


/**
 * Find the minimum value and replace it with the first value
 *
 * @param data Array of data
 * @return Array
 */

function finMinReplace(data){
    var minPos = 0;
    for(i=0;i<data.length;i++){
        if(data[i+1]<data[minPos]){
            minPos = i+1;
        }
    }
    var temp = data[0];
    data[0] = data[minPos];
    data[minPos] = temp;
  
    return data;
}

/**
 * Find the maximum value and replace it with the first value
 *
 * @param data Array of data
 * @return Array
 */

function finMaxReplace(data){
    var maxPos = 0;
    for(i=0;i<data.length;i++){
        if(data[i+1]>data[maxPos]){
            maxPos = i+1;
        }
    }
    var temp = data[0];
    data[0] = data[maxPos];
    data[maxPos] = temp;
}
        

No comments:

Post a Comment