diff --git a/01_introduction_to_algorithms/scala/01_introduction_to_algorithms.scala b/01_introduction_to_algorithms/scala/01_introduction_to_algorithms.scala new file mode 100644 index 0000000..30edf68 --- /dev/null +++ b/01_introduction_to_algorithms/scala/01_introduction_to_algorithms.scala @@ -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)) diff --git a/02_selection_sort/scala/01_selection_sort.scala b/02_selection_sort/scala/01_selection_sort.scala new file mode 100644 index 0000000..9eb0047 --- /dev/null +++ b/02_selection_sort/scala/01_selection_sort.scala @@ -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))