Skip to content

Instantly share code, notes, and snippets.

@sugiartocokrowibowo
Forked from khannedy/FindMaximum.scala
Last active August 29, 2015 14:14
Show Gist options
  • Save sugiartocokrowibowo/01fbb89eb88dd096a024 to your computer and use it in GitHub Desktop.
Save sugiartocokrowibowo/01fbb89eb88dd096a024 to your computer and use it in GitHub Desktop.
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