From eec9c310ff2390b33c98225aa52ded6b09a69a8c Mon Sep 17 00:00:00 2001 From: chase-g Date: Fri, 13 Oct 2017 11:37:51 -0400 Subject: [PATCH] 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 --- .../scala/01_introduction_to_algorithms.scala | 18 +++++++++++++ .../scala/01_selection_sort.scala | 25 +++++++++++++++++++ 2 files changed, 43 insertions(+) create mode 100644 01_introduction_to_algorithms/scala/01_introduction_to_algorithms.scala create mode 100644 02_selection_sort/scala/01_selection_sort.scala 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))