Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Breadth-First Search, Heap Sort #15

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions BreadthFirstSearch/BreadthFirstSearch.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package breadthfirstsearch

fun <T:Comparable<T>>breadthFirstSearch(start: T, edges:MutableList<Pair<T, T>>) {
val visited = mutableListOf<T>()
val queue = ArrayList<T>()

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<String>) {
println("Breath First Search: ")

val edges = ArrayList<Pair<Char, Char>>()
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)
}

39 changes: 39 additions & 0 deletions BreadthFirstSearch/README.markdown
Original file line number Diff line number Diff line change
@@ -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 <T:Comparable<T>>breadthFirstSearch(start: T, edges:MutableList<Pair<T, T>>) {
val visited = mutableListOf<T>()
val queue = ArrayList<T>()

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")
}
}
}
}
```
117 changes: 117 additions & 0 deletions Heap/Heap.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
package heap

class MaxHeap<T: Comparable<T>> {
val heap = ArrayList<T>()
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<T> {
val result = ArrayList<T>()
val copy = ArrayList<T>()
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<String>) {
println("Heap: ")

val heap = MaxHeap<Int>()
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()
}
63 changes: 63 additions & 0 deletions Heap/README.markdown
Original file line number Diff line number Diff line change
@@ -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
}
```
3 changes: 2 additions & 1 deletion README.markdown
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -101,7 +102,7 @@ Special-purpose sorts:
- Threaded Binary Tree
- [Segment Tree]
- kd-Tree
- [Heap]
- [Heap](Heap/)
- Fibonacci Heap
- Trie
- [B-Tree]
Expand Down