Adding Scala example for Chapter 2 (#31)
* Add files via upload * Update 01_countdown.scala * Update 02_greet.scala * Update 02_greet.scala * Create scala * Delete scala * Add files via upload * Add files via upload * Add files via upload * Update 01_selection_sort.scala * Add files via upload
This commit is contained in:
@@ -0,0 +1,18 @@
|
|||||||
|
def binarySearch(list: List[Int], item: Int): Int = {
|
||||||
|
if(list.isEmpty) { println("Item not found"); return 0 }
|
||||||
|
val guessIndex = (list.length) / 2
|
||||||
|
val guess = list(guessIndex)
|
||||||
|
if(item == guess) guess
|
||||||
|
else if(item < guess){
|
||||||
|
val halfList = list.take(list.length / 2)
|
||||||
|
binarySearch(halfList, item)
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
val halfList = list.drop(1 + (list.length / 2))
|
||||||
|
binarySearch(halfList, item)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
val myList = List(1,3,5,7,9)
|
||||||
|
println(binarySearch(myList, 3))
|
||||||
|
println(binarySearch(myList, -1))
|
||||||
25
02_selection_sort/scala/01_selection_sort.scala
Normal file
25
02_selection_sort/scala/01_selection_sort.scala
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
//Finds the smallest value in an array
|
||||||
|
def findSmallest(arr: Array[Int]): Int = {
|
||||||
|
//Stores the smallest value
|
||||||
|
var smallest = arr(0)
|
||||||
|
for(i <- 1 until arr.length){
|
||||||
|
if(arr(i) < smallest) {
|
||||||
|
smallest = arr(i)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return smallest
|
||||||
|
}
|
||||||
|
|
||||||
|
//Sort array
|
||||||
|
def selectionSort(arr: Array[Int]): Array[Int] = {
|
||||||
|
val newArr = new Array[Int](arr.length)
|
||||||
|
for(i <- 0 until arr.length){
|
||||||
|
//Finds the smallest element in the array and adds it to the new array
|
||||||
|
val smallest = findSmallest(arr)
|
||||||
|
newArr(i) = smallest
|
||||||
|
//Sets current smallest value in array above largest value to avoid reusing values
|
||||||
|
arr(arr.indexOf(smallest)) = arr.max + 1
|
||||||
|
}
|
||||||
|
return newArr
|
||||||
|
}
|
||||||
|
selectionSort(Array(5, 3, 6, 2, 10))
|
||||||
Reference in New Issue
Block a user