Examples of commonly used data structures and algorithms in Swift.

Overview

Swift Structures

This project provides a framework for commonly used data structures and algorithms written in a new iOS development language called Swift. While details of many algorithms exists on Wikipedia, these implementations are often written as pseudocode, or are expressed in C or C++. With Swift now officially released, its general syntax should be familiar enough for most programmers to understand.

Audience

As a developer, you should already be familiar with the basics of programming. Beyond algorithms, this project also aims to provide an alternative for learning the basics of Swift. This includes implementations of many Swift-specific features such as optionals, extensions, protocols and generics. Beyond Swift, audiences should be familiar with Singleton and Factory design patterns along with sets, arrays and dictionaries.

Features

The project features code-level examples for the following items:

The Book

Now in its 4th edition and supporting Swift 4.2, the The Swift Algorithms Book features code and color illustrations that benefits students and professionals. As a collaborative open-source effort, I also welcome feedback and contribution from others.

Example

    //bfs traversal with inout closure function
    func traverse(_ startingv: Vertex, formula: (_ node: inout Vertex) -> ()) {

        
        //establish a new queue
        let graphQueue: Queue<Vertex> = Queue<Vertex>()
        
        
        //queue a starting vertex
        graphQueue.enQueue(startingv)
        
        
        while !graphQueue.isEmpty() {
            
            
            //traverse the next queued vertex - Swift 4.0
            //var vitem: Vertex! = graphQueue.deQueue()
            
            
            //traverse the next queued vertex
            guard var vitem = graphQueue.deQueue() else {
                break
            }
            
            //add unvisited vertices to the queue
            for e in vitem.neighbors {
                if e.neighbor.visited == false {
                    print("adding vertex: \(e.neighbor.key) to queue..")
                    graphQueue.enQueue(e.neighbor)
                }
            }
            
            //invoke formula
            formula(&vitem)

            
        } //end while
        
        
        print("graph traversal complete..")
                
    }

Getting Started

Swift Structures has been optimized for Swift 4.2 (e.g., Xcode 10.0) or later. The directories are organized as follows:

  • Source - Code for all Swift data structures, algorithms and source extensions
  • Example - An empty iOS single-view application template
  • SwiftTests - Unit tests with XCTest Framework

Usage

Individuals are welcome to use the code with commercial and open-source projects. As a courtesy, please provide attribution to waynewbishop.com. For more information, review the complete license agreement.

Branches

  • master - The production branch. Clone or fork this repository for the latest copy
  • develop - The active Swift 4.2 development branch. Swift 4.2 pull requests should be directed to this branch

Other Projects

  • EKAlgorithms - A set of computer exercises implemented in Objective-C
  • Algorithms - A playground for common questions implemented in Ruby

Questions

Have a question? Feel free to contact me on Twitter or online.

Comments
  • Code metrics improvements / code optimizations / production (readability/coupling/complexity)

    Code metrics improvements / code optimizations / production (readability/coupling/complexity)

    LinkedList optimizations: -added counter variable -added overflow/underflow exceptions -moved counter to read-only property -moved code to function nodeAtIndex function -changed variables to optionals for readability -removed overcompilcated code blocks -removed Enumerable constraint for T -removed print

    LLNode optimizations: -added default init and parametrized init to LLNode

    Tests modifications: -added try! code block to bypass exception handling

    opened by default-writer 9
  • Trie Update for Swift 2.0

    Trie Update for Swift 2.0

    I was trying to use the Trie code and the following had an error.

    let searchKey: String = keyword.substringToIndex(current.level + 1) can't convert Int to Index

    Fix it by casting to NSString let searchKey: String = (keyword as NSString).substringToIndex(current.level + 1)

    Also keyword.length becomes keyword.characters.count

    opened by rmoffett 5
  • Refactor Merge Sort Algorithm

    Refactor Merge Sort Algorithm

    We currently have a merge sort algorithm in our repo, but I feel this could be refactored into a more efficient / simplified model. The resulting code would be published in essay format.

    help wanted 
    opened by waynewbishop 4
  • Hash table should be implemented as Dictionary

    Hash table should be implemented as Dictionary

    The main advantage of hash table is quick access to elemets:

    Time complexity for hash tables (from wiki):

    | Type | Average | Worst case | | --- | --- | --- | | Space | O(n) | O(n) | | Search | O(1) | O(n) | | Insert | O(1) | O(n) | | Delete | O(1) | O(n) |

    Since your hash table implemented as loop in array - the average complexity of search is O(n), not O(1), that not fit this time complexity requirements of hash tables. For correct implementation of this structure hash table should be implemented as Dictionary

    opened by skywinder 4
  • Bug in `Queue.deQueue()`

    Bug in `Queue.deQueue()`

    I think there is a bug in the implementation of Queue.deQueue() . Consider the following code:

    var w = Queue<Int>()
    println(w.count) // prints "0" as expected
    w.enQueue(1)
    println(w.count) // prints "1" - as expected
    w.deQueue()
    println(w.count) // should print "0", but instead, you get a fatal error
    

    In xCode 6.3.1, this code in a playground gives the following fatal error: fatal error: unexpectedly found nil while unwrapping an Optional value Playground execution failed: Execution was interrupted, reason: EXC_BAD_INSTRUCTION

    This is due to the fact that deQueue() at line 102 sets top to nil when there is no next item in the queue. count then blows up when it tries to access top.key which is an implicitly unwrapped optional. A fix would be to instead set top to QNode<T>() on 102.

    opened by JenkinsJB 3
  • Extend Sorting Algorithms as Array Extension?

    Extend Sorting Algorithms as Array Extension?

    Sorting is one of most popular essays at www.waynewbishop.com. As part of this I would like refactor the article to include the newly added examples of Quick Sort and Merge Sort. The essay illustrations should also be redone or removed.

    www.waynewbishop.com/swift/sorting-algorithms

    opened by waynewbishop 3
  • Binary Search Bug Fix and Update for Testing

    Binary Search Bug Fix and Update for Testing

    Problem

    When searching for a key within a non-complete array (e.g. [0,4,7,9,13,16,34] as opposed to [0,1,2,3,4,5,6,7]) the binarySearch() function returns an initial correct print statement followed by a false positive.

    Run:

    sorting.binarySearch([0,4,7,9,13,16,34], key: 8)

    Result:

       search value 8 not found..
       search value 8 found..
    

    Solution implemented this PR

    • Updated binarySearch(_:) to be testable (now returns true or false depending on whether the key was found in the sequence)
    • Updated the test to test all possible values of a given array
    opened by normand1 2
  • Code metrics improvements / code optimizations / production (readability/coupling/complexity)

    Code metrics improvements / code optimizations / production (readability/coupling/complexity)

    LinkedList optimizations: -added counter variable -added overflow/underflow exceptions -moved counter to read-only property -moved code to function nodeAtIndex function -changed variables to optionals for readability -removed overcompilcated code blocks -removed Enumerable constraint for T -removed print

    LLNode optimizations: -added default init and parametrized init to LLNode

    Tests modifications: -added try! code block to bypass exception handling

    opened by default-writer 2
  • Redundant / Unnecessary Parentheses

    Redundant / Unnecessary Parentheses

    In Swift, parentheses in loops / control structures are optional. They often times make readability easier, but in some cases can also overly complicate the code. It is up to you whether you want to use them or not, but there are a couple of places in this project in which I feel they could be removed. Here is an example:

    In Source/Factories/LinkedList.swift:

    //the number of items
        var count: Int {
    
                if (head.key == nil) {
                    return 0
                }
    
                else  {
    
                    var current: LLNode = head
                    var x: Int = 1
    
    
                    //cycle through the list of items
                    while ((current.next) != nil) {
                        current = current.next!
                        x++
                    }
    
                    return x
    
                }
        }
    

    I think that we could change the code, for example in the if statement, to be:

    var count: Int {
    
                if head.key == nil {
                    return 0
                }
    

    and in the while loop:

    //cycle through the list of items
                    while current.next != nil {
                        current = current.next!
                        x++
                    }
    

    Again, up to you, the author, but I think it could help Swift learners looking at this code to recognize some of the readability features of Swift versus Objective-C.

    opened by hoke-t 2
  • Remove

    Remove "times" integer extension

    Hi Richard;

    Just making some notes. When refactoring the merge sort it looks like we can also remove this extension as well.

    extension Int {
    
        //iterates the closure body a specified number of times
        func times(closure:(Int)->Void) {
            for i in 0...self {
                closure(i)
            }
        }
    
    }
    
    opened by waynewbishop 2
  • Fixed QuickSort algorithm. Added tests for QuickSort

    Fixed QuickSort algorithm. Added tests for QuickSort

    I've fixed implementation of QuickSort. New implementation ensures O(n log n) complexity for case when array contains duplicates. Old realisation provided quadratic time for such cases. I've added tests to check QuickSort with different cases - with duplicates, with different array sized, already sorted array.

    opened by n0an 1
  • Fixed crash when removing the first node from a LinkedList with a cou…

    Fixed crash when removing the first node from a LinkedList with a cou…

    …nt of 1

    This crash can be reproduced by creating a new LinkedList, adding a value, and then immediately removing it. The crash occurs because head.next is nil.

    Additionally, I moved the index == 0 check before the initialization of current, as it doesn't need to use it.

    I can change the ternary operator to an if-statement if you think it's more readable.

    opened by malmazuke 3
Releases(v4.1)
  • v4.1(Jan 9, 2018)

    This is a quick note announcing an updated version of the Swift Algorithms Book. For those who’ve previously purchased the PDF version, all reference materials (including further reading) are now hyperlinked. Chapter headings are also clickable to specific sections in the document. Changes to both the EPUB and PDF versions include the following:

    Revised LinkList.remove(at:) algorithm Renamed methods for HashTable algorithm and Keyable Protocol Revised content for Stacks & Queues Revised content for Basic Sorting

    Source code(tar.gz)
    Source code(zip)
  • v4.0(Sep 25, 2017)

    Swift 4.0 is now officially released! As a result, The Swift Algorithms project has been updated to reflect this new standard.

    Change Summary

    The relative stability of Swift 4.0 has allowed an opportunity refine many areas of the code base. Notable updates include:

    • New examples of code Memoization and Dynamic Programming
    • New non-recursive Binary Search Tree Algorithm (BST)
    • New contains() method for BST's.
    • New generic min/max Heap Algorithm
    • New unit test cases for evaluating Fibonacci and Heap Algorithms
    • subscript syntax applied to Trie and Linked List algorithms
    • Support for new Swift-based Array.swapAt function
    • Limited use of Implicit Unwrapped Optionals (IUO's)

    Existing Swift 3.0 followers should study the new Swift 4.0 BST Algorithm. To simulate a call stack often employed in recursive processes, this model uses a custom Stack data structure in conjunction with inout variables.

    Follow the latest Swift 4.0 code updates from the master branch. If you have questions or would like submit a pull request, please do so using the develop branch.

    Source code(tar.gz)
    Source code(zip)
  • v3.0-beta.6(Aug 31, 2016)

    With the final version of Swift 3.0 soon to be announced, the algorithms project has been updated to reflect the latest standard!

    Change Summary

    This update incorporates final language changes to Swift 3.0. These include minor functional changes to declare inout parameters, optionals, cast operations and infix operators.

    Branches

    Follow the latest Swift 3.0 code updates here. While Swift 3.0 remains in beta, the master project branch will continue to support Swift 2.2.

    Source code(tar.gz)
    Source code(zip)
  • v3.0-beta.3(Jul 27, 2016)

    With Swift 3.0 now available in beta, the algorithms project has been updated to reflect this new standard!

    Change Summary

    There have been many language refinements introduced with Swift 3.0. This has provided an opportunity to also refine numerous areas of the algorithms project. Notable Swift 3.0 proposals now supported include:

    Existing Swift 2.2 followers should study the revamped Swift 3.0 collection indexing model. This implementation can seen with the refactored String extension and new Sortable protocol extension.

    Additional Refinements

    New Int and Array extensions have been added to support pre-existing Math and Sorting classes (respectively). Beyond centralizing specific operations, the new design now works directly with the recursive Enum project example. Finally, a general effort has been made to improve generics (where applicable). This includes refactoring Hash Tables (renamed Hash Lists) to support generic objects as well as the Search and Sorting algorithms.

    Branches

    Follow the latest Swift 3.0 code updates here. While Swift 3.0 remains in beta, the master project branch will continue to support Swift 2.2.

    Source code(tar.gz)
    Source code(zip)
  • v2.2(Apr 7, 2016)

    With Swift 2.2 now available, the algorithms project has been updated to reflect this new standard!

    Change Summary

    This release mainly addresses legacy C-style syntax. With the pending removal of C-style loops as well as increment / decrement markers in Swift 3.0, Github examples for bubbleSort, insertionSort and selectionSort have been refactored. Minor updates were also made to queues, stacks and linked lists. While not officially published, the Math-based fibonacci methods were also updated to reflect non-mutating parameters.

    Source code(tar.gz)
    Source code(zip)
  • v.2.1(Dec 2, 2015)

    With The Swift Algorithms Book now available in print, pdf and ePub formats, it's been great receiving feedback from people everywhere! One area of interest has been sorting and search. Beyond heaps, graphs and binary search trees (BST's), language newcomers have been curious to see how Swift handles traditional sorting algorithms like bubbleSort() and insertionSort().

    Change Summary

    Github examples for bubbleSort, insertionSort and selectionSort now support generic and non-generic implementations using the latest Swift 2 syntax. Also, two new versions of binarySearch are now available. To support these updates, SortingTest.swift has also been refactored to support generic and non-generic methods.

    Source code(tar.gz)
    Source code(zip)
  • v2.0(Sep 11, 2015)

    The introduction of Swift 2.0 brings a new level of usability and concise syntax many have come to appreciate. As the referring source for The Swift Algorithms Book, the Github source has been updated to meet this new standard.

    Change Summary

    While most updates involved object mutability and basic syntax, significant refactoring was completed for the project extensions. Mainly used as helper functions for trie algorithms, readers should see little difference with the latest code and examples published in the book.

    Along with code updates, this release also introduces a new algorithm called a Bloom Filter. Similar to a hash table, stay tuned for new documentation at waynewbishop.com that describes this process.

    Source code(tar.gz)
    Source code(zip)
Owner
Wayne Bishop
Wayne Bishop
Algorithms and data structures in Swift, with explanations!

Welcome to the Swift Algorithm Club! Here you'll find implementations of popular algorithms and data structures in everyone's favorite new language Sw

raywenderlich 27.3k Jan 8, 2023
EKAlgorithms contains some well known CS algorithms & data structures.

EKAlgorithms EKAlgorithms is a set of computer exercises implemented in Objective-C. Data structures, well known algorithms, CS curiosities, you name

Evgeny Karkan 2.4k Jan 4, 2023
Simple implementations of various dynamic data structures in Swift.

SwiftDataStructures Example To run the example project, clone the repo, and run pod install from the Example directory first. Requirements Installatio

Hector Delgado 0 Oct 21, 2021
Mendel - Swift miliframework for implementing evolutionary/genetic algorithms

Mendel Mendel - Swift miliframework for implementing evolutionary/genetic algorithms. Or, you know, Gregor Mendel. This started out as an exercise in

saniul 139 Oct 26, 2022
Swivl - A set of BLAS-accelerated linerar algebra structures and functions

Swivl - Swift Vector Library A set of BLAS-accelerated linerar algebra structure

null 0 Jan 19, 2022
Algorithm is a library of tools that is used to create intelligent applications.

Welcome to Algorithm Algorithm is a library of tools that is used to create intelligent applications. Features Probability Tools Expected Value Progra

Cosmicmind 820 Dec 9, 2022
KeyPathKit is a library that provides the standard functions to manipulate data along with a call-syntax that relies on typed keypaths to make the call sites as short and clean as possible.

KeyPathKit Context Swift 4 has introduced a new type called KeyPath, with allows to access the properties of an object with a very nice syntax. For in

Vincent Pradeilles 406 Dec 25, 2022
A Graph Data Structure in Pure Swift

SwiftGraph SwiftGraph is a pure Swift (no Cocoa) implementation of a graph data structure, appropriate for use on all platforms Swift supports (iOS, m

David Kopec 700 Dec 16, 2022
The simplest abstraction to synchronize local data with remote source. For iOS, wirtten in swift.

Purpose The simplest abstraction to synchronize local data with remote source. For iOS, written in swift. Overview Many applications uses remote serve

Siarhei Ladzeika 7 Mar 17, 2022
Arena is an implementation of the generational arena data structure in Swift.

Arena This package is very much work in progress. Arena is an implementation of the generational arena data structure in Swift. An Arena is useful for

null 7 Dec 7, 2021
Swift-extensions - Swift package extending the Swift programming language.

swift-extensions A package containing extensions for the Swift programming language. Contribution Reporting a bug If you find a bug, please open a bug

Alexandre H. Saad 2 Jun 12, 2022
Swift μ-framework for efficient array diffs and datasource adapters.

Buffer Swift μ-framework for efficient array diffs, collection observation and data source implementation. C++11 port here Installation cd {PROJECT_RO

Alex Usbergo 348 Aug 2, 2022
Swift library to generate differences and patches between collections.

Differ Differ generates the differences between Collection instances (this includes Strings!). It uses a fast algorithm (O((N+M)*D)) to do this. Featu

Tony Arnold 628 Dec 29, 2022
A Swift probability and statistics library

Probably Probably is a set of Swift structures for computing the probability and cumulative distributions of different probablistic functions. Right n

Harlan Haskins 270 Dec 2, 2022
💻 A fast and flexible O(n) difference algorithm framework for Swift collection.

A fast and flexible O(n) difference algorithm framework for Swift collection. The algorithm is optimized based on the Paul Heckel's algorithm. Made wi

Ryo Aoyama 3.3k Jan 4, 2023
:droplet: A generic view model for both basic and complex scenarios

Brick Description Brick is a generic view model for both basic and complex scenarios. Mapping a basic table view cells is as easy as pie, if you have

HyperRedink 59 Jul 31, 2021
Differific - a fast and convenient diffing framework.

Differific Description Differific is a diffing tool that helps you compare Hashable objects using the Paul Heckel's diffing algorithm. Creating a chan

Christoffer Winterkvist 127 Jun 3, 2022
Extension of Diffable API which allow not duplicate code and use less models. Included example for SideBar.

SPDiffable Apple's diffable API requerid models for each object type. If you want use it in many place, you pass many time to implemenet and get over

Ivan Vorobei 114 Jan 3, 2023
Fast sorted collections for Swift using in-memory B-trees

Fast Sorted Collections for Swift Using In-Memory B-Trees Overview Reference Documentation Optimizing Collections: The Book What Are B-Trees? Why In-M

null 1.3k Dec 20, 2022