Skip to content

Commit eec9c31

Browse files
chase-gegonSchiele
authored andcommitted
Adding Scala example for Chapter 2 (egonSchiele#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
1 parent 7d6d36c commit eec9c31

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
def binarySearch(list: List[Int], item: Int): Int = {
2+
if(list.isEmpty) { println("Item not found"); return 0 }
3+
val guessIndex = (list.length) / 2
4+
val guess = list(guessIndex)
5+
if(item == guess) guess
6+
else if(item < guess){
7+
val halfList = list.take(list.length / 2)
8+
binarySearch(halfList, item)
9+
}
10+
else {
11+
val halfList = list.drop(1 + (list.length / 2))
12+
binarySearch(halfList, item)
13+
}
14+
}
15+
16+
val myList = List(1,3,5,7,9)
17+
println(binarySearch(myList, 3))
18+
println(binarySearch(myList, -1))
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
//Finds the smallest value in an array
2+
def findSmallest(arr: Array[Int]): Int = {
3+
//Stores the smallest value
4+
var smallest = arr(0)
5+
for(i <- 1 until arr.length){
6+
if(arr(i) < smallest) {
7+
smallest = arr(i)
8+
}
9+
}
10+
return smallest
11+
}
12+
13+
//Sort array
14+
def selectionSort(arr: Array[Int]): Array[Int] = {
15+
val newArr = new Array[Int](arr.length)
16+
for(i <- 0 until arr.length){
17+
//Finds the smallest element in the array and adds it to the new array
18+
val smallest = findSmallest(arr)
19+
newArr(i) = smallest
20+
//Sets current smallest value in array above largest value to avoid reusing values
21+
arr(arr.indexOf(smallest)) = arr.max + 1
22+
}
23+
return newArr
24+
}
25+
selectionSort(Array(5, 3, 6, 2, 10))

0 commit comments

Comments
 (0)