├── 01_BinarySearch ├── 01_BinarySearch.iml └── src │ └── BinarySearch.java ├── 02_SelectionSort ├── 02_SelectionSort.iml └── src │ ├── SelectionSort.java │ └── SelectionSort2.java ├── 03_Recursion ├── 03_Recursion.iml └── src │ ├── Countdown.java │ ├── Factorial.java │ └── Greet.java ├── 04_Quicksort ├── 04_Quicksort.iml └── src │ ├── LoopSum.java │ ├── Quicksort.java │ ├── RecursiveCount.java │ ├── RecursiveMax.java │ └── RecursiveSum.java ├── 05_HashTables ├── 05_HashTables.iml └── src │ ├── CheckVoter.java │ └── PriceOfGroceries.java ├── 06_BreadthFirstSearch ├── 06_BreadthFirstSearch.iml └── src │ └── BreadthFirstSearch.java ├── 07_DijkstrasAlgorithm ├── 07_DijkstrasAlgorithm.iml └── src │ └── DijkstrasAlgorithm.java ├── 08_GreedyAlgorithms ├── 08_GreedyAlgorithms.iml └── src │ └── SetCovering.java ├── 09_DynamicProgramming ├── 09_DynamicProgramming.iml └── src │ └── LongestCommonSubsequence.java ├── README.md └── Бхаргава А. - Грокаем Алгоритмы. Иллюстрированное пособие для программистов и любопытствущих - 2017.PDF /01_BinarySearch/01_BinarySearch.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /01_BinarySearch/src/BinarySearch.java: -------------------------------------------------------------------------------- 1 | public class BinarySearch { 2 | 3 | // has to return boxed integer in order to comfort to interface defined in the book 4 | private static Integer binarySearch(int[] list, int item) { 5 | int low = 0; 6 | int high = list.length - 1; 7 | 8 | while (low <= high) { 9 | int mid = (low + high) / 2; 10 | int guess = list[mid]; 11 | if (guess == item) { 12 | return mid; 13 | } 14 | if (guess > item) { 15 | high = mid - 1; 16 | } else { 17 | low = mid + 1; 18 | } 19 | } 20 | 21 | return null; 22 | } 23 | 24 | public static void main(String[] args) { 25 | int[] myList = {1, 3, 5, 7, 9}; 26 | 27 | System.out.println(binarySearch(myList, 5)); // 1 28 | System.out.println(binarySearch(myList, -1)); // null 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /02_SelectionSort/02_SelectionSort.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /02_SelectionSort/src/SelectionSort.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.Arrays; 3 | import java.util.List; 4 | 5 | public class SelectionSort { 6 | 7 | private static List selectionSort(List arr) { 8 | List newArr = new ArrayList<>(arr.size()); 9 | 10 | int size = arr.size(); 11 | for (int i = 0; i < size; i++) { 12 | int smallest = findSmallest(arr); 13 | newArr.add(arr.get(smallest)); 14 | 15 | arr.remove(smallest); 16 | } 17 | 18 | return newArr; 19 | } 20 | 21 | private static int findSmallest(List arr) { 22 | int smallest = arr.get(0); 23 | int smallestIndex = 0; 24 | for (int i = 0; i < arr.size(); i++) { 25 | if (arr.get(i) < smallest) { 26 | smallest = arr.get(i); 27 | smallestIndex = i; 28 | } 29 | } 30 | return smallestIndex; 31 | } 32 | 33 | public static void main(String[] args) { 34 | List arr = new ArrayList<>(Arrays.asList(5, 3, 6, 2, 10)); 35 | System.out.println(selectionSort(arr)); //[2, 3, 5, 6, 10] 36 | } 37 | } -------------------------------------------------------------------------------- /02_SelectionSort/src/SelectionSort2.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | public class SelectionSort2 { 4 | 5 | // this version uses raw arrays instead of ArrayList 6 | private static int[] selectionSort(int[] arr) { 7 | int[] newArr = new int[]{arr.length}; 8 | 9 | for (int i = 0; i < newArr.length; i++) { 10 | int smallest = findSmallest(arr, i); 11 | newArr[i] = arr[smallest]; 12 | } 13 | 14 | return newArr; 15 | } 16 | 17 | private static int findSmallest(int[] arr, int low) { 18 | int smallest = arr[low]; 19 | int smallestIndex = low; 20 | for (int i = low + 1; i < arr.length; i++) { 21 | if (arr[i] < smallest) { 22 | smallest = arr[i]; 23 | smallestIndex = i; 24 | } 25 | } 26 | return smallestIndex; 27 | } 28 | 29 | public static void main(String[] args) { 30 | int[] arr = {5, 3, 6, 2, 10}; 31 | System.out.println(Arrays.toString(selectionSort(arr))); // [2, 3, 5, 6, 10] 32 | } 33 | } -------------------------------------------------------------------------------- /03_Recursion/03_Recursion.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /03_Recursion/src/Countdown.java: -------------------------------------------------------------------------------- 1 | public class Countdown { 2 | 3 | private static void countdown(int i) { 4 | System.out.println(i); 5 | 6 | // base case 7 | if (i <= 0) { 8 | return; 9 | } else { 10 | countdown(i - 1); 11 | } 12 | } 13 | 14 | public static void main(String[] args) { 15 | countdown(5); 16 | } 17 | } -------------------------------------------------------------------------------- /03_Recursion/src/Factorial.java: -------------------------------------------------------------------------------- 1 | public class Factorial { 2 | 3 | private static int fact(int x) { 4 | if (x == 1) { 5 | return 1; 6 | } else { 7 | return x * fact(x - 1); 8 | } 9 | } 10 | 11 | public static void main(String[] args) { 12 | System.out.println(fact(5)); 13 | } 14 | } -------------------------------------------------------------------------------- /03_Recursion/src/Greet.java: -------------------------------------------------------------------------------- 1 | public class Greet { 2 | 3 | private static void greet2(String name) { 4 | System.out.println("how are you, " + name + "?"); 5 | } 6 | 7 | private static void bye() { 8 | System.out.println("ok bye!"); 9 | } 10 | 11 | private static void greet(String name) { 12 | System.out.println("hello, " + name + "!"); 13 | greet2(name); 14 | System.out.println("getting ready to say bye..."); 15 | bye(); 16 | } 17 | 18 | public static void main(String[] args) { 19 | greet("adit"); 20 | } 21 | } -------------------------------------------------------------------------------- /04_Quicksort/04_Quicksort.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /04_Quicksort/src/LoopSum.java: -------------------------------------------------------------------------------- 1 | public class LoopSum { 2 | 3 | private static int sum(int[] arr) { 4 | int total = 0; 5 | for (int x = 0; x < arr.length; x++) { 6 | total += arr[x]; 7 | } 8 | 9 | return total; 10 | } 11 | 12 | public static void main(String[] args) { 13 | System.out.println(sum(new int[]{1, 2, 3, 4})); // 10 14 | } 15 | } -------------------------------------------------------------------------------- /04_Quicksort/src/Quicksort.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | import java.util.List; 3 | import java.util.function.Function; 4 | import java.util.stream.Collectors; 5 | import java.util.stream.Stream; 6 | 7 | public class Quicksort { 8 | public static void main(String[] args) { 9 | System.out.println(quicksort(Arrays.asList(10, 5, 2, 3))); // [2, 3, 5, 10] 10 | } 11 | 12 | private static List quicksort(List list) { 13 | if (list.size() < 2) { 14 | // base case, arrays with 0 or 1 element are already "sorted" 15 | return list; 16 | } else { 17 | // recursive case 18 | Integer pivot = list.get(0); 19 | 20 | // sub-array of all the elements less than the pivot 21 | List less = list.stream().skip(1).filter(el -> el <= pivot) 22 | .collect(Collectors.toList()); 23 | 24 | // sub-array of all the elements greater than the pivot 25 | List greater = list.stream().skip(1).filter(el -> el > pivot) 26 | .collect(Collectors.toList()); 27 | 28 | return Stream.of( 29 | quicksort(less).stream(), 30 | Stream.of(pivot), 31 | quicksort(greater).stream()) 32 | .flatMap(Function.identity()).collect(Collectors.toList()); 33 | } 34 | } 35 | } -------------------------------------------------------------------------------- /04_Quicksort/src/RecursiveCount.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | public class RecursiveCount { 4 | 5 | private static int count(int[] list) { 6 | if (list.length == 0) { 7 | return 0; 8 | } 9 | 10 | return 1 + count(Arrays.copyOfRange(list, 1, list.length)); 11 | } 12 | 13 | public static void main(String[] args) { 14 | System.out.println(count(new int[]{0, 1, 2, 3, 4, 5})); // 6 15 | } 16 | } -------------------------------------------------------------------------------- /04_Quicksort/src/RecursiveMax.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | public class RecursiveMax { 4 | 5 | private static int max(int[] list) { 6 | if (list.length == 2) { 7 | return list[0] > list[1] ? list[0] : list[1]; 8 | } 9 | 10 | int subMax = max(Arrays.copyOfRange(list, 1, list.length)); 11 | return list[0] > subMax ? list[0] : subMax; 12 | } 13 | 14 | public static void main(String[] args) { 15 | System.out.println(max(new int[]{1, 5, 10, 25, 16, 1})); // 25 16 | } 17 | } -------------------------------------------------------------------------------- /04_Quicksort/src/RecursiveSum.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | public class RecursiveSum { 4 | 5 | private static int sum(int[] arr) { 6 | if (arr.length == 0) { 7 | return 0; 8 | } else { 9 | return arr[0] + sum(Arrays.copyOfRange(arr, 1, arr.length)); 10 | } 11 | } 12 | 13 | public static void main(String[] args) { 14 | System.out.println(sum(new int[]{1, 2, 3, 4})); // 10 15 | } 16 | } -------------------------------------------------------------------------------- /05_HashTables/05_HashTables.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /05_HashTables/src/CheckVoter.java: -------------------------------------------------------------------------------- 1 | import java.util.HashMap; 2 | import java.util.Map; 3 | 4 | public class CheckVoter { 5 | private static Map voted = new HashMap<>(); 6 | 7 | private static void checkVoter(String name) { 8 | if (voted.containsKey(name)) { 9 | System.out.println("kick them out!"); 10 | } else { 11 | voted.put(name, true); 12 | System.out.println("let them vote!"); 13 | } 14 | } 15 | 16 | public static void main(String[] args) { 17 | checkVoter("tom"); // let them vote! 18 | checkVoter("mike"); // let them vote! 19 | checkVoter("mike"); // kick them out! 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /05_HashTables/src/PriceOfGroceries.java: -------------------------------------------------------------------------------- 1 | import java.util.HashMap; 2 | import java.util.Map; 3 | 4 | public class PriceOfGroceries { 5 | 6 | public static void main(String[] args) { 7 | Map book = new HashMap<>(); 8 | 9 | // an apple costs 67 cents 10 | book.put("apple", 0.67); 11 | // milk costs $1.49 12 | book.put("milk", 1.49); 13 | book.put("avocado", 1.49); 14 | 15 | System.out.println(book); // {apple=0.67, avocado=1.49, milk=1.49} 16 | } 17 | } -------------------------------------------------------------------------------- /06_BreadthFirstSearch/06_BreadthFirstSearch.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /06_BreadthFirstSearch/src/BreadthFirstSearch.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class BreadthFirstSearch { 4 | private static Map> graph = new HashMap<>(); 5 | 6 | private static boolean search(String name) { 7 | Queue searchQueue = new ArrayDeque<>(graph.get(name)); 8 | // This list is how you keep track of which people you've searched before. 9 | List searched = new ArrayList<>(); 10 | 11 | while (!searchQueue.isEmpty()) { 12 | String person = searchQueue.poll(); 13 | // Only search this person if you haven't already searched them 14 | if (!searched.contains(person)) { 15 | if (person_is_seller(person)) { 16 | System.out.println(person + " is a mango seller!"); 17 | } else { 18 | searchQueue.addAll(graph.get(person)); 19 | // Marks this person as searched 20 | searched.add(person); 21 | } 22 | } 23 | } 24 | 25 | return false; 26 | } 27 | 28 | private static boolean person_is_seller(String name) { 29 | return name.endsWith("m"); 30 | } 31 | 32 | public static void main(String[] args) { 33 | graph.put("you", Arrays.asList("alice", "bob", "claire")); 34 | graph.put("bob", Arrays.asList("anuj", "peggy")); 35 | graph.put("alice", Arrays.asList("peggy")); 36 | graph.put("claire", Arrays.asList("thom", "jonny")); 37 | graph.put("anuj", Collections.emptyList()); 38 | graph.put("peggy", Collections.emptyList()); 39 | graph.put("thom", Collections.emptyList()); 40 | graph.put("jonny", Collections.emptyList()); 41 | 42 | search("you"); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /07_DijkstrasAlgorithm/07_DijkstrasAlgorithm.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /07_DijkstrasAlgorithm/src/DijkstrasAlgorithm.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.HashMap; 3 | import java.util.List; 4 | import java.util.Map; 5 | 6 | public class DijkstrasAlgorithm { 7 | // the graph 8 | private static Map> graph = new HashMap<>(); 9 | private static List processed = new ArrayList<>(); 10 | 11 | private static String findLowestCostNode(Map costs) { 12 | Double lowestCost = Double.POSITIVE_INFINITY; 13 | String lowestCostNode = null; 14 | 15 | // Go through each node 16 | for (Map.Entry node : costs.entrySet()) { 17 | Double cost = node.getValue(); 18 | // If it's the lowest cost so far and hasn't been processed yet... 19 | if (cost < lowestCost && !processed.contains(node.getKey())) { 20 | // ... set it as the new lowest-cost node. 21 | lowestCost = cost; 22 | lowestCostNode = node.getKey(); 23 | } 24 | } 25 | 26 | return lowestCostNode; 27 | } 28 | 29 | public static void main(String[] args) { 30 | graph.put("start", new HashMap<>()); 31 | graph.get("start").put("a", 6.0); 32 | graph.get("start").put("b", 2.0); 33 | 34 | graph.put("a", new HashMap<>()); 35 | graph.get("a").put("fin", 1.0); 36 | 37 | graph.put("b", new HashMap<>()); 38 | graph.get("b").put("a", 3.0); 39 | graph.get("b").put("fin", 5.0); 40 | 41 | graph.put("fin", new HashMap<>()); 42 | 43 | // The costs table 44 | Map costs = new HashMap<>(); 45 | costs.put("a", 6.0); 46 | costs.put("b", 2.0); 47 | costs.put("fin", Double.POSITIVE_INFINITY); 48 | 49 | // the parents table 50 | Map parents = new HashMap<>(); 51 | parents.put("a", "start"); 52 | parents.put("b", "start"); 53 | parents.put("fin", null); 54 | 55 | String node = findLowestCostNode(costs); 56 | while (node != null) { 57 | Double cost = costs.get(node); 58 | // Go through all the neighbors of this node 59 | 60 | Map neighbors = graph.get(node); 61 | 62 | for (String n : neighbors.keySet()) { 63 | double newCost = cost + neighbors.get(n); 64 | // If it's cheaper to get to this neighbor by going through this node 65 | if (costs.get(n) > newCost) { 66 | // ... update the cost for this node 67 | costs.put(n, newCost); 68 | // This node becomes the new parent for this neighbor. 69 | parents.put(n, node); 70 | } 71 | } 72 | // Mark the node as processed 73 | processed.add(node); 74 | 75 | // Find the next node to process, and loop 76 | node = findLowestCostNode(costs); 77 | } 78 | 79 | System.out.println("Cost from the start to each node:"); 80 | System.out.println(costs); // { a: 5, b: 2, fin: 6 } 81 | } 82 | } -------------------------------------------------------------------------------- /08_GreedyAlgorithms/08_GreedyAlgorithms.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /08_GreedyAlgorithms/src/SetCovering.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class SetCovering { 4 | 5 | public static void main(String[] args) { 6 | Set statesNeeded = new HashSet(Arrays.asList("mt", "wa", "or", "id", "nv", "ut", "ca", "az")); 7 | Map> stations = new LinkedHashMap<>(); 8 | 9 | stations.put("kone", new HashSet<>(Arrays.asList("id", "nv", "ut"))); 10 | stations.put("ktwo", new HashSet<>(Arrays.asList("wa", "id", "mt"))); 11 | stations.put("kthree", new HashSet<>(Arrays.asList("or", "nv", "ca"))); 12 | stations.put("kfour", new HashSet<>(Arrays.asList("nv", "ut"))); 13 | stations.put("kfive", new HashSet<>(Arrays.asList("ca", "az"))); 14 | 15 | Set finalStations = new HashSet(); 16 | while (!statesNeeded.isEmpty()) { 17 | String bestStation = null; 18 | Set statesCovered = new HashSet<>(); 19 | 20 | for (Map.Entry> station : stations.entrySet()) { 21 | Set covered = new HashSet<>(statesNeeded); 22 | covered.retainAll(station.getValue()); 23 | 24 | if (covered.size() > statesCovered.size()) { 25 | bestStation = station.getKey(); 26 | statesCovered = covered; 27 | } 28 | statesNeeded.removeIf(statesCovered::contains); 29 | 30 | if (bestStation != null) { 31 | finalStations.add(bestStation); 32 | } 33 | } 34 | } 35 | System.out.println(finalStations); // [ktwo, kone, kthree, kfive] 36 | } 37 | } -------------------------------------------------------------------------------- /09_DynamicProgramming/09_DynamicProgramming.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /09_DynamicProgramming/src/LongestCommonSubsequence.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | public class LongestCommonSubsequence { 4 | public static void main(String[] args) { 5 | // if (word_a[i] == word_b[1]) { 6 | // cell[i][j] = cell[i - 1][j - 1] + 1; 7 | // } else { 8 | // cell[i][j] = Math.Max(cell[i - 1][j], cell[i][j - 1]); 9 | // } 10 | 11 | String wordA = "hish"; 12 | String wordB = "fish"; 13 | 14 | int[][] cell = new int[wordA.length()][wordB.length()]; 15 | 16 | for (int i = 0; i < wordA.length(); i++) { 17 | for (int j = 0; j < wordB.length(); j++) { 18 | // The letters match 19 | if (wordA.charAt(i) == wordB.charAt(j)) { 20 | if (i > 0 && j > 0) { 21 | cell[i][j] = cell[i - 1][j - 1] + 1; 22 | } else { 23 | cell[i][j] = 1; 24 | } 25 | } else { 26 | // The letters don't match. 27 | if (i > 0 && j > 0) { 28 | cell[i][j] = Math.max(cell[i - 1][j], cell[i][j - 1]); 29 | } else { 30 | cell[i][j] = 0; 31 | } 32 | } 33 | } 34 | } 35 | 36 | printResult(cell); 37 | // [0, 0, 0, 1] 38 | // [0, 1, 1, 1] 39 | // [0, 1, 2, 2] 40 | // [0, 1, 2, 3] 41 | 42 | } 43 | 44 | private static void printResult(int[][] arr) { 45 | for (int[] row : arr) { 46 | System.out.println(Arrays.toString(row)); 47 | } 48 | } 49 | 50 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # GrokkingAlgorithms 2 | java samples of Grokking Algorithm book by Aditya Y. Bhargava 3 | -------------------------------------------------------------------------------- /Бхаргава А. - Грокаем Алгоритмы. Иллюстрированное пособие для программистов и любопытствущих - 2017.PDF: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mduisenov/GrokkingAlgorithms/52fc3434f8577bb15d3977aff9ebe630c6140b44/Бхаргава А. - Грокаем Алгоритмы. Иллюстрированное пособие для программистов и любопытствущих - 2017.PDF --------------------------------------------------------------------------------