Algorithms and data structures in Swift, with explanations!
Swift Other
Latest commit 10abdbc Jan 16, 2017 @kelvinlauKL kelvinlauKL committed on GitHub Update README.markdown
Updated the Z-algorithm link to the String Search section.
Permalink
Failed to load latest commit information.
AVL Tree Fix Access Control position in AVLTree Dec 27, 2016
All-Pairs Shortest Paths Migrates App-Pairs Shortest Paths to Swift3 syntax Jan 5, 2017
Array2D update Array2D, Deque to swift3.0 Nov 24, 2016
B-Tree fixed typos in B-Tree README Dec 4, 2016
Binary Search Tree Updating to Swift3 (enum lowercase) Dec 29, 2016
Binary Search Removing "a" label from binarySearch method in playground so it match… Aug 20, 2016
Binary Tree Update README in Binary Tree Dec 14, 2016
Bit Set Updating to Swift3 Aug 30, 2016
Bloom Filter Updating to Swift3 Aug 30, 2016
Bounded Priority Queue Fixes README file for Swift3. Sep 18, 2016
Boyer-Moore Removed redundant validation. Dec 25, 2016
Breadth-First Search Fix link to Minimum Spanning Tree (Unweighted) Nov 29, 2016
Brute-Force String Search Migrating Brute Force String Search to Swift3 Sep 26, 2016
Bubble Sort Updated formatting and grammar errors Aug 21, 2016
Bucket Sort move the text cases to swift 3 syntax Nov 27, 2016
Comb Sort Added Comb Sort test. Jan 10, 2017
Combinatorics migrate combinatorics to swift3 Oct 27, 2016
Count Occurrences Update Count Occurrences to Swift 3 Aug 31, 2016
Counting Sort Updating to Swift3 (enum lowercase) Dec 29, 2016
Depth-First Search migrating dfs to swift3 Sep 26, 2016
Deque update Array2D, Deque to swift3.0 Nov 24, 2016
DiningPhilosophers Update README.md Jan 14, 2017
Fixed Size Array Changed tabs from 4 spaces to 2 spaces. Updated README file to reflec… Nov 1, 2016
Fizz Buzz updated fizzBuzz to swift3 Sep 20, 2016
GCD Upgrade to Swift3 Sep 18, 2016
Graph update readme Oct 27, 2016
Hash Set migratehashsetswift3 Oct 31, 2016
Hash Table Update hash table for Swift 3.0 Sep 17, 2016
HaversineDistance update readme Oct 11, 2016
Heap Sort Remove playground. Dec 28, 2016
Heap Convert to swift 3.0 syntax. Dec 28, 2016
Huffman Coding aligning with style guidelines Jan 5, 2017
Images Image size change Jun 4, 2016
Insertion Sort Update Insertion Sort to Swift 3 Aug 31, 2016
K-Means Updated K-Means Tests.xcodeproj to latest settings. Jan 8, 2017
Karatsuba Multiplication Fix mistake in the formula that simplifies to (a*d + b*c) Nov 12, 2016
Knuth-Morris-Pratt edited Knuth-Morris-Pratt README Oct 1, 2016
Kth Largest Element make some conversion Sep 20, 2016
Linear Regression Update README Nov 9, 2016
Linear Search Update Linear Search to Swift 3 Aug 31, 2016
Linked List Merge pull request #311 from nerdo/master Jan 11, 2017
Longest Common Subsequence Fix method name from reverse() to reversed() in README.markdown Oct 14, 2016
Merge Sort Removed Extra Spaces. Jan 8, 2017
Minimum Edit Distance Update code and README for Swift 3.0 Nov 24, 2016
Minimum Spanning Tree (Unweighted) Warning correction for unused return function Jan 4, 2017
Monty Hall Problem migrating montyhall to swift 3 Sep 27, 2016
Ordered Array updated readme Sep 22, 2016
Ordered Set updated Ordered Set to swift 3 Sep 22, 2016
Palindromes Add shared scheme to test Project for tests Dec 26, 2016
Priority Queue updated Priority Queue to swift 3 Sep 22, 2016
Queue Update Stack and Queue files to use top and front properties (#351) Jan 12, 2017
Quicksort Changed README to reflect Swift 3 migration. Sep 18, 2016
Radix Sort Added tests for RadixSort. Jan 13, 2017
Radix Tree Radix tree re-indent to use two spaces Oct 5, 2016
Red-Black Tree Make each steps clear Dec 28, 2016
Ring Buffer update readme Oct 27, 2016
Rootish Array Stack Fixed comment spacing in playground Dec 22, 2016
Run-Length Encoding Merge branch 'master' of https://github.com/raywenderlich/swift-algor… Jun 12, 2016
Segment Tree Fix a bug in SegmentTree Nov 2, 2016
Select Minimum Maximum Fixed indentation of the code. Jan 2, 2017
Selection Sampling took off an extra min Nov 1, 2016
Selection Sort Update Selection Sort to Swift 3 Sep 10, 2016
Set Cover (Unweighted) Set cover (unweighted) - replacing count = 0 conditions with isEmpty Jun 28, 2016
Shell Sort Update to Swift 3.0 Oct 17, 2016
Shortest Path (Unweighted) Updated with XCTest Swift3 syntax for shortest path Jan 3, 2017
Shuffle Merge pull request #273 from TheIronBorn/patch-5 Oct 31, 2016
Shunting Yard Updating to Swift3 (enum lowercase) Dec 29, 2016
Single-Source Shortest Paths (Weighted) Update Target to Swift 3.0 Jan 15, 2017
Skip-List Clean up Oct 22, 2016
Slow Sort Added SlowSort Jul 16, 2016
Stack Update Stack and Queue files to use top and front properties (#351) Jan 12, 2017
Ternary Search Tree fixing failing test (#355) Jan 11, 2017
Threaded Binary Tree Added basic SwiftLint config file. Fixing all linting errors. Jun 8, 2016
Topological Sort Migrated Topological Sort to Swift 3 Oct 15, 2016
Treap Migrate treap to swift 3 Oct 8, 2016
Tree Fix code in Tree docs (set parent to weak) Nov 5, 2016
Trie Fixes compile error due to missing brace. Jan 10, 2017
Two-Sum Problem update readme Oct 21, 2016
Union-Find Updating to Swift 3 Aug 30, 2016
Z-Algorithm Modified Z-Algorithm to conform to our style guide. Jan 16, 2017
swift-algorithm-club.xcworkspace Migrates Ternary Search Tree to Swift 3 syntax (#352) Jan 11, 2017
.gitignore No longer gitignore xcworkspace May 9, 2016
.swiftlint.yml Added basic SwiftLint config file. Fixing all linting errors. Jun 8, 2016
.travis.yml Merge pull request #353 from taiheng/feature/swift3-radixsort Jan 15, 2017
Algorithm Design.markdown Tons of tiny text tweaks Mar 3, 2016
Big-O Notation.markdown Add link to rosettacode.org Feb 19, 2016
How to Contribute.markdown Merge branch 'master' of https://github.com/raywenderlich/swift-algor… Jun 12, 2016
LICENSE.txt Add name to articles Jan 28, 2016
README.markdown Update README.markdown Jan 16, 2017
Under Construction.markdown Set cover (unweighted) - adding link on under construction page Jun 28, 2016
What are Algorithms.markdown Pancakes! Feb 10, 2016
Why Algorithms.markdown Tweak main page Feb 6, 2016
install_swiftlint.sh CHMOD install_swiftlint.sh Jun 8, 2016

README.markdown

Swift Algorithm Club

Welcome to the Swift Algorithm Club!

Here you'll find implementations of popular algorithms and data structures in everyone's favorite new language Swift, with detailed explanations of how they work.

If you're a computer science student who needs to learn this stuff for exams -- or if you're a self-taught programmer who wants to brush up on the theory behind your craft -- you've come to the right place!

The goal of this project is to explain how algorithms work. The focus is on clarity and readability of the code, not on making a reusable library that you can drop into your own projects. That said, most of the code should be ready for production use but you may need to tweak it to fit into your own codebase.

Most code is compatible with Xcode 8.2 and Swift 3. We'll keep this updated with the latest version of Swift.

This is a work in progress. More algorithms will be added soon. :-)

😍 Suggestions and contributions are welcome! 😍

Important links

What are algorithms and data structures? Pancakes!

Why learn algorithms? Worried this isn't your cup of tea? Then read this.

Big-O notation. We often say things like, "This algorithm is O(n)." If you don't know what that means, read this first.

Algorithm design techniques. How do you create your own algorithms?

How to contribute. Report an issue to leave feedback, or submit a pull request.

Under construction. Algorithms that are under construction.

Where to start?

If you're new to algorithms and data structures, here are a few good ones to start out with:

The algorithms

Searching

String Search

  • Brute-Force String Search. A naive method.
  • Boyer-Moore. A fast method to search for substrings. It skips ahead based on a look-up table, to avoid looking at every character in the text.
  • Knuth-Morris-Pratt
  • Rabin-Karp
  • Longest Common Subsequence. Find the longest sequence of characters that appear in the same order in both strings.
  • Z-Algorithm. Finds all instances of a pattern in a String, and returns the indexes of where the pattern starts within the String.

Sorting

It's fun to see how sorting algorithms work, but in practice you'll almost never have to provide your own sorting routines. Swift's own sort() is more than up to the job. But if you're curious, read on...

Basic sorts:

Fast sorts:

Special-purpose sorts:

Bad sorting algorithms (don't use these!):

Compression

Miscellaneous

  • Shuffle. Randomly rearranges the contents of an array.
  • Comb Sort. An improve upon the Bubble Sort algorithm.

Mathematics

Machine learning

Data structures

The choice of data structure for a particular task depends on a few things.

First, there is the shape of your data and the kinds of operations that you'll need to perform on it. If you want to look up objects by a key you need some kind of dictionary; if your data is hierarchical in nature you want a tree structure of some sort; if your data is sequential you want a stack or queue.

Second, it matters what particular operations you'll be performing most, as certain data structures are optimized for certain actions. For example, if you often need to find the most important object in a collection, then a heap or priority queue is more optimal than a plain array.

Most of the time using just the built-in Array, Dictionary, and Set types is sufficient, but sometimes you may want something more fancy...

Variations on arrays

  • Array2D. A two-dimensional array with fixed dimensions. Useful for board games.
  • Bit Set. A fixed-size sequence of n bits.
  • Fixed Size Array. When you know beforehand how large your data will be, it might be more efficient to use an old-fashioned array with a fixed size.
  • Ordered Array. An array that is always sorted.
  • Rootish Array Stack. A space and time efficient variation on Swift arrays.

Queues

  • Stack. Last-in, first-out!
  • Queue. First-in, first-out!
  • Deque. A double-ended queue.
  • Priority Queue. A queue where the most important element is always at the front.
  • Ring Buffer. Also known as a circular buffer. An array of a certain size that conceptually wraps around back to the beginning.

Lists

  • Linked List. A sequence of data items connected through links. Covers both singly and doubly linked lists.
  • Skip-List. Skip List is a probablistic data-structure with same logarithmic time bound and efficiency as AVL/ or Red-Black tree and provides a clever compromise to efficiently support search and update operations.

Trees

  • Tree. A general-purpose tree structure.
  • Binary Tree. A tree where each node has at most two children.
  • Binary Search Tree (BST). A binary tree that orders its nodes in a way that allows for fast queries.
  • Red-Black Tree
  • Splay Tree
  • Threaded Binary Tree
  • Segment Tree. Can quickly compute a function over a portion of an array.
  • kd-Tree
  • Heap. A binary tree stored in an array, so it doesn't use pointers. Makes a great priority queue.
  • Fibonacci Heap
  • Trie. A special type of tree used to store associative data structures.
  • B-Tree. A self-balancing search tree, in which nodes can have more than two children.

Hashing

  • Hash Table. Allows you to store and retrieve objects by a key. This is how the dictionary type is usually implemented.
  • Hash Functions

Sets

  • Bloom Filter. A constant-memory data structure that probabilistically tests whether an element is in a set.
  • Hash Set. A set implemented using a hash table.
  • Multiset
  • Ordered Set. A set where the order of items matters.

Graphs

Puzzles

A lot of software developer interview questions consist of algorithmic puzzles. Here is a small selection of fun ones. For more puzzles (with answers), see here and here.

Learn more!

For more information, check out these great books:

The following books are available for free online:

Other algorithm repositories:

  • EKAlgorithms. A great collection of algorithms in Objective-C.
  • @lorentey. Production-quality Swift implementations of common algorithms and data structures.
  • Rosetta Code. Implementations in pretty much any language you can think of.
  • AlgorithmVisualizer. Visualize algorithms on your browser.
  • Swift Structures Data Structures with directions on how to use them here

Credits

The Swift Algorithm Club was originally created by Matthijs Hollemans.

It is now maintained by Chris Pilcher and Kelvin Lau.

The Swift Algorithm Club is a collaborative effort from the most algorithmic members of the raywenderlich.com community. We're always looking for help - why not join the club? :]

License

All content is licensed under the terms of the MIT open source license.

Build Status