diff --git a/BreadthFirstSearch/BreadthFirstSearch.kt b/BreadthFirstSearch/BreadthFirstSearch.kt new file mode 100644 index 0000000..09987bc --- /dev/null +++ b/BreadthFirstSearch/BreadthFirstSearch.kt @@ -0,0 +1,43 @@ +package breadthfirstsearch + +fun >breadthFirstSearch(start: T, edges:MutableList>) { + val visited = mutableListOf() + val queue = ArrayList() + + queue.add(start) + visited.add(start) + + var front: T + + loop@while(queue.isNotEmpty()) { + front = queue[0] + queue.removeAt(0) + println("start vertex $front") + + for(edge in edges) { + if(edge.first == front + && !visited.contains(edge.second)) { + val next = edge.second + queue.add(next) + visited.add(next) + println("next vertex enqueue $next") + } + } + } +} + +fun main(args: Array) { + println("Breath First Search: ") + + val edges = ArrayList>() + edges.add('a' to 'b') + edges.add('a' to 'c') + edges.add('b' to 'd') + edges.add('b' to 'e') + edges.add('c' to 'f') + edges.add('c' to 'g') + edges.add('e' to 'h') + + breadthFirstSearch('a', edges) +} + diff --git a/BreadthFirstSearch/README.markdown b/BreadthFirstSearch/README.markdown new file mode 100644 index 0000000..1c9bd8f --- /dev/null +++ b/BreadthFirstSearch/README.markdown @@ -0,0 +1,39 @@ +# Breadth-First Search + +Breadth-first search (BFS) is an algorithm for traversing or searching tree or graph data structures. It starts at the tree root (or some arbitrary node of a graph, sometimes referred to as a 'search key'), and explores all of the neighbor nodes at the present depth prior to moving on to the nodes at the next depth level. + +It uses the opposite strategy as depth-first search, which instead explores the highest-depth nodes first before being forced to backtrack and expand shallower nodes. + +BFS and its application in finding connected components of graphs were invented in 1945 by Konrad Zuse, in his (rejected) Ph.D. thesis on the Plankalkül programming language, but this was not published until 1972. It was reinvented in 1959 by Edward F. Moore, who used it to find the shortest path out of a maze, and later developed by C. Y. Lee into a wire routing algorithm (published 1961). + +source:Wikipedia + +## The Code + +```kotlin +fun >breadthFirstSearch(start: T, edges:MutableList>) { + val visited = mutableListOf() + val queue = ArrayList() + + queue.add(start) + visited.add(start) + + var front: T + + loop@while(queue.isNotEmpty()) { + front = queue[0] + queue.removeAt(0) + println("start vertex $front") + + for(edge in edges) { + if(edge.first == front + && !visited.contains(edge.second)) { + val next = edge.second + queue.add(next) + visited.add(next) + println("next vertex enqueue $next") + } + } + } +} +``` \ No newline at end of file diff --git a/Heap/Heap.kt b/Heap/Heap.kt new file mode 100644 index 0000000..504ad2f --- /dev/null +++ b/Heap/Heap.kt @@ -0,0 +1,117 @@ +package heap + +class MaxHeap> { + val heap = ArrayList() + var isMinHeap = true + + fun getRootIndex(i: Int): Int? { + if(i == 0) return null + return (i - 1) / 2 + } + + fun getLeftChildIndex(i: Int): Int? { + val left = 2 * i + 1 + return if (left < heap.size) left else null + } + + fun getRightChildIndex(i: Int): Int? { + val right = 2 * i + 2 + return if (right < heap.size) right else null + } + + fun insert(element: T) { + heap.add(element) + var idx = heap.lastIndex + while(idx > 0 + && getRootIndex(idx) != null + && heap[getRootIndex(idx)!!] < heap[idx]) { + getRootIndex(idx)?.let { + val temp = heap[idx] + heap[idx] = heap[it] + heap[it] = temp + idx = it + } + } + } + + fun remove(): T { + val result = heap[0] + heap[0] = heap[heap.lastIndex] + heap.removeAt(heap.lastIndex) + + var here = 0 + loop@while(true) { + + val left = getLeftChildIndex(here) + val right = getRightChildIndex(here) + if(left == null) break@loop + + var next = here + if(heap[next] < heap[left] + && (right == null + || heap[left] > heap[right])) { + next = left + } else if(right != null + && heap[next] < heap[right]) { + next = right + } + if(next == here) break@loop + + val temp = heap[here] + heap[here] = heap[next] + heap[next] = temp + + here = next + } + + return result + } + + fun sort(): ArrayList { + val result = ArrayList() + val copy = ArrayList() + copy.addAll(heap) + + while(heap.size > 0) { + result.add(remove()) + } + + heap.addAll(copy) + return result + } + + fun print() { + heap.forEach { + print("${it.toString()} ") + } + println() + } +} + +fun main(args: Array) { + println("Heap: ") + + val heap = MaxHeap() + heap.insert(4) + heap.print() + heap.insert(2) + heap.print() + heap.insert(10) + heap.print() + heap.insert(3) + heap.print() + heap.insert(1) + heap.print() + heap.insert(5) + heap.print() + heap.insert(7) + heap.print() + heap.insert(9) + heap.print() + + print("sort: ") + heap.sort().forEach { + print("$it ") + } + println() +} \ No newline at end of file diff --git a/Heap/README.markdown b/Heap/README.markdown new file mode 100644 index 0000000..ffa81af --- /dev/null +++ b/Heap/README.markdown @@ -0,0 +1,63 @@ +# Heap + +In computer science, a heap is a specialized tree-based data structure which is essentially an almost complete[1] tree that satisfies the heap property: if P is a parent node of C, then the key (the value) of P is either greater than or equal to (in a max heap) or less than or equal to (in a min heap) the key of C.[2] The node at the "top" of the heap (with no parents) is called the root node. + +The heap is one maximally efficient implementation of an abstract data type called a priority queue, and in fact priority queues are often referred to as "heaps", regardless of how they may be implemented. A common implementation of a heap is the binary heap, in which the tree is a binary tree (see figure). The heap data structure, specifically the binary heap, was introduced by J. W. J. Williams in 1964, as a data structure for the heapsort sorting algorithm.[3] Heaps are also crucial in several efficient graph algorithms such as Dijkstra's algorithm. + +In a heap, the highest (or lowest) priority element is always stored at the root. A heap is not a sorted structure and can be regarded as partially ordered. When a heap is a complete binary tree, it has a smallest possible height—a heap with N nodes and for each node a branches always has loga N height. A heap is a useful data structure when you need to remove the object with the highest (or lowest) priority. + +Note that, as shown in the graphic, there is no implied ordering between siblings or cousins and no implied sequence for an in-order traversal (as there would be in, e.g., a binary search tree). The heap relation mentioned above applies only between nodes and their parents, grandparents, etc. The maximum number of children each node can have depends on the type of heap, but in many types it is at most two, which is known as a binary heap. + +source:Wikipedia + +## The Code + +```kotlin +fun insert(element: T) { + heap.add(element) + var idx = heap.lastIndex + while(idx > 0 + && getRootIndex(idx) != null + && heap[getRootIndex(idx)!!] < heap[idx]) { + getRootIndex(idx)?.let { + val temp = heap[idx] + heap[idx] = heap[it] + heap[it] = temp + idx = it + } + } +} + +fun remove(): T { + val result = heap[0] + heap[0] = heap[heap.lastIndex] + heap.removeAt(heap.lastIndex) + + var here = 0 + loop@while(true) { + + val left = getLeftChildIndex(here) + val right = getRightChildIndex(here) + if(left == null) break@loop + + var next = here + if(heap[next] < heap[left] + && (right == null + || heap[left] > heap[right])) { + next = left + } else if(right != null + && heap[next] < heap[right]) { + next = right + } + if(next == here) break@loop + + val temp = heap[here] + heap[here] = heap[next] + heap[next] = temp + + here = next + } + + return result +} +``` \ No newline at end of file diff --git a/README.markdown b/README.markdown index fb75e05..ae1daa4 100644 --- a/README.markdown +++ b/README.markdown @@ -19,6 +19,7 @@ This is a work in progress. More algorithms will be added soon. :-) - [Selection Sampling] - [Union-Find] - [Depth-First Search](DepthFirstSearch/) +- [Breadth-First Search](BreadthFirstSearch/) ### String Search @@ -101,7 +102,7 @@ Special-purpose sorts: - Threaded Binary Tree - [Segment Tree] - kd-Tree -- [Heap] +- [Heap](Heap/) - Fibonacci Heap - Trie - [B-Tree]