Skip to content

Instantly share code, notes, and snippets.

@davidinga
davidinga / BinarySearch.swift
Created August 24, 2019 02:38
Iterative Binary Search algorithm implemented in Swift. Returns an optional index given a target element and an array of the same type. Time complexity of O(logn) and space complexity of O(1).
func binarySearch<Element>(for target: Element, in array: [Element]) -> Int? where Element: Comparable {
var L = 0
var R = array.count - 1
var mid = 0
while L <= R {
//// Index of middle element.
mid = L + (R - L) / 2
//// Middle element is target; return it.
@davidinga
davidinga / HeapSort.swift
Created August 23, 2019 23:16
Stand-alone HeapSort implementation in Swift. Uses MaxHeap properties to sort elements in an array.
private func heapify<Element>(_ array: inout [Element], _ count: Int, _ index: Int) where Element: Comparable {
var largest = index
let l = 2 * index + 1
let r = 2 * index + 2
//// Check if left child exists and is greater than parent.
if l < count && array[index] < array[l] {
largest = l
}
@davidinga
davidinga / MergeSort.swift
Created August 22, 2019 21:00
Recursive MergeSort implementation in Swift. Sorts an array of generic type, Element, when Element conforms to the Comparable protocol.
func mergeSort<Element>(array: inout [Element]) where Element: Comparable {
if array.count > 1 {
let mid = array.count / 2
var L = Array(array[..<mid])
var R = Array(array[mid...])
mergeSort(array: &L)
mergeSort(array: &R)
var i = 0, j = 0, k = 0
@davidinga
davidinga / QuickSort.swift
Created August 21, 2019 18:24
Recursive QuickSort implementation that extends Array. Pivot set to the last element in the partition.
extension Array where Element: Comparable {
private func partition(array: inout [Element], low: Int, high: Int) -> Int {
let pivot = array[high]
var i = low - 1
for j in low..<high {
if array[j] <= pivot {
i += 1
array.swapAt(i, j)
}
}
@davidinga
davidinga / RadixSort.swift
Created August 20, 2019 20:33
Extends Array<Int> to include Radix Sort. Uses Counting Sort as a subroutine. This implementation is for nonnegative, base 10 integers.
extension Array where Element == Int {
mutating func radixSort() {
let radix = 10
var digit = 1
var done = false
var unsortedArray = self
while !done {
done = true
/// Counting Sort: Step 1
/// - Tally each number in count array.
@davidinga
davidinga / FindPalindromeLinkedList.swift
Created July 7, 2019 22:00
Determines if a linked list is a palindrome. Both solutions work for a singly or doubly linked list.
func isPalindrome(_ list: DoublyLinkedList<String>) -> Bool {
// Simple solution. Iterate over linked list and store as string.
// Uses linear space and time.
// Then compare string to a reversed string.
// If equal, then we have a palindrome.
var node = list.first
var string = ""
while node != nil {
string += String(node!.element)
node = node!.next
@davidinga
davidinga / ShiftZerosInArray.swift
Created June 21, 2019 00:32
Shift all zeros in array to the right most indexes in linear time.
func shiftZeros(in array: inout [Int]) {
var indexToPlaceZero = array.count - 1
for i in array.indices {
if array[i] == 0 {
while array[indexToPlaceZero] == 0, i < indexToPlaceZero {
indexToPlaceZero -= 1
}
array.swapAt(i, indexToPlaceZero)
}
}
@davidinga
davidinga / HashTableOnlyKeys.swift
Last active June 17, 2019 20:22
Hash Table with chaining that stores the keys only.
struct HashTableOnlyKeys<Key: Hashable> {
typealias Element = Key
typealias List = SinglyLinkedList<Element>
private var table: [List]
private(set) public var count = 0
public var size: Int {
return table.count
@davidinga
davidinga / Heap.swift
Created June 13, 2019 01:55
Builds a Min-Heap or Max-Heap
public struct Heap<Element> {
var elements: [Element]
var priorityFunction: (Element, Element) -> Bool
init(elements: [Element] = [], priorityFunction: @escaping (Element, Element) -> Bool) {
self.elements = elements
self.priorityFunction = priorityFunction
buildHeap()
}
@davidinga
davidinga / InsertionSort.swift
Created June 13, 2019 01:35
Extends Swift's Array data type to include Insertion Sort Algorithm.
extension Array where Element: Comparable {
mutating func insertionSort() {
for (i, element) in self.enumerated() {
var i = i
while i > 0 && element < self[i - 1] {
self[i] = self[i - 1]
i -= 1
}