-
-
Save sugiartocokrowibowo/01fbb89eb88dd096a024 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.khannedy.algorithm.array | |
import scala.annotation.tailrec | |
/** | |
* @author Eko Khannedy | |
* @since 11/8/14 | |
*/ | |
object FindMaximum { | |
/** | |
* Find maximum value in array using for-loop | |
* @param array array of Int | |
* @return maximum value | |
*/ | |
def searchByLoop(array: Array[Int]) = { | |
var temp = 0 | |
for (i <- 0 until array.length) { | |
if (temp < array(i)) { | |
temp = array(i) | |
} | |
} | |
temp | |
} | |
/** | |
* Find maximum value in array using recursive | |
* @param array array of Int | |
* @return maximum value | |
*/ | |
def searchByRecursive(array: Array[Int]) = { | |
@tailrec | |
def searchRecursive(max: Int, index: Int): Int = { | |
if (index >= array.length) max | |
else if (max < array(index)) searchRecursive(array(index), index + 1) | |
else searchRecursive(max, index + 1) | |
} | |
searchRecursive(0, 0) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment