Convert Figma logo to code with AI

kodecocodes logoswift-algorithm-club

Algorithms and data structures in Swift, with explanations!

28,724
5,002
28,724
61

Top Related Projects

Algorithms and data structures in Swift, with explanations!

Commonly used sequence and collection algorithms for Swift

📖 Design Patterns implemented in Swift 5.0

A curated list of awesome iOS ecosystem, including Objective-C and Swift Projects

A collaborative list of awesome Swift libraries and resources. Feel free to contribute!

swift implementation of flappy bird. More at fullstackedu.com

Quick Overview

The Swift Algorithm Club is a GitHub repository that provides implementations of various algorithms and data structures in Swift. It serves as an educational resource for developers to learn about algorithms and their Swift implementations, offering detailed explanations and examples for each topic.

Pros

  • Comprehensive collection of algorithms and data structures
  • Well-documented code with explanations and complexity analysis
  • Actively maintained and updated for newer Swift versions
  • Includes unit tests for most implementations

Cons

  • Some implementations may not be optimized for production use
  • Not all algorithms have playground examples
  • Occasional inconsistencies in coding style across different contributors
  • Some advanced topics may lack detailed explanations

Code Examples

  1. Binary Search implementation:
func binarySearch<T: Comparable>(_ a: [T], key: T) -> Int? {
    var lowerBound = 0
    var upperBound = a.count
    while lowerBound < upperBound {
        let midIndex = lowerBound + (upperBound - lowerBound) / 2
        if a[midIndex] == key {
            return midIndex
        } else if a[midIndex] < key {
            lowerBound = midIndex + 1
        } else {
            upperBound = midIndex
        }
    }
    return nil
}
  1. Quicksort implementation:
func quicksort<T: Comparable>(_ a: [T]) -> [T] {
    guard a.count > 1 else { return a }

    let pivot = a[a.count/2]
    let less = a.filter { $0 < pivot }
    let equal = a.filter { $0 == pivot }
    let greater = a.filter { $0 > pivot }

    return quicksort(less) + equal + quicksort(greater)
}
  1. Stack implementation:
struct Stack<Element> {
    private var storage: [Element] = []
    
    mutating func push(_ element: Element) {
        storage.append(element)
    }
    
    mutating func pop() -> Element? {
        return storage.popLast()
    }
    
    func peek() -> Element? {
        return storage.last
    }
    
    var isEmpty: Bool {
        return storage.isEmpty
    }
}

Getting Started

To use the Swift Algorithm Club in your project:

  1. Clone the repository:

    git clone https://github.com/kodecocodes/swift-algorithm-club.git
    
  2. Navigate to the desired algorithm or data structure folder.

  3. Copy the Swift file(s) into your project.

  4. Import the file in your Swift code:

    import Foundation
    // Use the algorithm or data structure
    let result = binarySearch([1, 2, 3, 4, 5], key: 3)
    
  5. For playground examples, open the .playground file in Xcode to interact with the implementation.

Competitor Comparisons

Algorithms and data structures in Swift, with explanations!

Pros of swift-algorithm-club

  • Comprehensive collection of algorithms and data structures implemented in Swift
  • Well-documented code with explanations and examples
  • Active community and regular updates

Cons of swift-algorithm-club

  • Large repository size may be overwhelming for beginners
  • Some implementations may not be optimized for production use
  • Limited focus on Swift-specific optimizations

Code Comparison

Both repositories contain the same codebase, as they are identical. Here's an example of a binary search implementation from swift-algorithm-club:

func binarySearch<T: Comparable>(_ a: [T], key: T) -> Int? {
  var lowerBound = 0
  var upperBound = a.count
  while lowerBound < upperBound {
    let midIndex = lowerBound + (upperBound - lowerBound) / 2
    if a[midIndex] == key {
      return midIndex
    } else if a[midIndex] < key {
      lowerBound = midIndex + 1
    } else {
      upperBound = midIndex
    }
  }
  return nil
}

Both repositories are identical, containing the same content, structure, and code. They appear to be mirrors or duplicates of the same project, likely maintained by the same organization (kodecocodes) for redundancy or different purposes.

Commonly used sequence and collection algorithms for Swift

Pros of swift-algorithms

  • Official Apple project, ensuring high-quality and well-maintained code
  • Focuses on production-ready, optimized algorithms for real-world use
  • Seamlessly integrates with the Swift Standard Library

Cons of swift-algorithms

  • Limited scope, covering fewer algorithms compared to swift-algorithm-club
  • Less educational content and explanations for beginners
  • Primarily targets advanced developers and production environments

Code Comparison

swift-algorithms:

let numbers = [1, 4, 2, 3, 5]
let combinations = numbers.combinations(ofCount: 3)
print(Array(combinations))
// Output: [[1, 4, 2], [1, 4, 3], [1, 4, 5], [1, 2, 3], [1, 2, 5], [1, 3, 5], [4, 2, 3], [4, 2, 5], [4, 3, 5], [2, 3, 5]]

swift-algorithm-club:

let numbers = [1, 4, 2, 3, 5]
let combinations = combinations(numbers, k: 3)
print(combinations)
// Output: [[1, 2, 3], [1, 2, 4], [1, 2, 5], [1, 3, 4], [1, 3, 5], [1, 4, 5], [2, 3, 4], [2, 3, 5], [2, 4, 5], [3, 4, 5]]

The swift-algorithms repository provides a more integrated and Swift-idiomatic approach, while swift-algorithm-club offers a standalone implementation that may be easier to understand for educational purposes.

📖 Design Patterns implemented in Swift 5.0

Pros of Design-Patterns-In-Swift

  • Focuses specifically on design patterns, providing a comprehensive resource for Swift developers
  • Includes real-world examples and use cases for each design pattern
  • Regularly updated with Swift language updates and new patterns

Cons of Design-Patterns-In-Swift

  • Limited scope compared to swift-algorithm-club, which covers a broader range of algorithms and data structures
  • May not be as suitable for beginners learning Swift fundamentals
  • Less community engagement and contributions compared to swift-algorithm-club

Code Comparison

Design-Patterns-In-Swift (Singleton pattern):

class Singleton {
    static let shared = Singleton()
    private init() {}
}

swift-algorithm-club (Binary Search implementation):

func binarySearch<T: Comparable>(_ a: [T], key: T) -> Int? {
    var lowerBound = 0
    var upperBound = a.count
    while lowerBound < upperBound {
        let midIndex = lowerBound + (upperBound - lowerBound) / 2
        if a[midIndex] == key {
            return midIndex
        } else if a[midIndex] < key {
            lowerBound = midIndex + 1
        } else {
            upperBound = midIndex
        }
    }
    return nil
}

The code examples highlight the different focus areas of each repository. Design-Patterns-In-Swift demonstrates concise implementations of design patterns, while swift-algorithm-club provides more complex algorithm implementations with detailed explanations.

A curated list of awesome iOS ecosystem, including Objective-C and Swift Projects

Pros of awesome-ios

  • Comprehensive collection of iOS development resources, libraries, and tools
  • Regularly updated with new content and community contributions
  • Covers a wide range of iOS development topics beyond algorithms

Cons of awesome-ios

  • Less focused on in-depth explanations and implementations of algorithms
  • May be overwhelming for beginners due to the sheer volume of information
  • Lacks hands-on coding examples for most listed resources

Code comparison

swift-algorithm-club provides detailed algorithm implementations, while awesome-ios primarily lists resources. Here's a brief example:

swift-algorithm-club (Binary Search implementation):

func binarySearch<T: Comparable>(_ a: [T], key: T) -> Int? {
  var lowerBound = 0
  var upperBound = a.count
  while lowerBound < upperBound {
    let midIndex = lowerBound + (upperBound - lowerBound) / 2
    if a[midIndex] == key {
      return midIndex
    } else if a[midIndex] < key {
      lowerBound = midIndex + 1
    } else {
      upperBound = midIndex
    }
  }
  return nil
}

awesome-ios doesn't provide code examples but instead offers links to relevant libraries and resources.

Summary

swift-algorithm-club focuses on in-depth algorithm implementations and explanations, making it ideal for learning specific algorithms and data structures in Swift. awesome-ios, on the other hand, serves as a comprehensive directory of iOS development resources, covering a broader range of topics but with less depth in algorithm-specific content.

A collaborative list of awesome Swift libraries and resources. Feel free to contribute!

Pros of awesome-swift

  • Broader scope, covering various Swift-related resources beyond algorithms
  • Regularly updated with new Swift libraries, tools, and resources
  • Organized into categories for easy navigation and discovery

Cons of awesome-swift

  • Less focused on in-depth algorithm implementations
  • May lack detailed explanations or code examples for each resource
  • Can be overwhelming due to the large number of links and resources

Code comparison

While a direct code comparison isn't relevant due to the nature of these repositories, here's a brief example of how they differ in content:

swift-algorithm-club:

func binarySearch<T: Comparable>(_ a: [T], key: T) -> Int? {
  var lowerBound = 0
  var upperBound = a.count
  while lowerBound < upperBound {
    let midIndex = lowerBound + (upperBound - lowerBound) / 2
    // ... (implementation continues)

awesome-swift:

## Algorithm
*Algorithms implemented in Swift*

* [swift-algorithm-club](https://github.com/raywenderlich/swift-algorithm-club) - Algorithms and data structures in Swift, with explanations!
* [SwiftLCS](https://github.com/Frugghi/SwiftLCS) :penguin: - implementation of the longest common subsequence (LCS) algorithm in Swift.

The swift-algorithm-club repository focuses on detailed algorithm implementations, while awesome-swift provides curated lists of resources, including links to algorithm-related projects.

swift implementation of flappy bird. More at fullstackedu.com

Pros of FlappySwift

  • Focused on a specific game implementation, providing a practical example of Swift in game development
  • Offers a complete, playable game project, ideal for learning game mechanics and Swift simultaneously
  • Simpler codebase, making it easier for beginners to understand and modify

Cons of FlappySwift

  • Limited in scope, focusing only on one game type rather than a broad range of algorithms
  • Less comprehensive in terms of Swift language features and advanced programming concepts
  • May become outdated more quickly as it's tied to a specific game trend

Code Comparison

FlappySwift (game logic):

func didBegin(_ contact: SKPhysicsContact) {
    if moving.speed > 0 {
        if ( contact.bodyA.categoryBitMask & scoreCategory ) == scoreCategory || ( contact.bodyB.categoryBitMask & scoreCategory ) == scoreCategory {
            score += 1
            scoreLabelNode.text = String(score)
            scoreLabelNode.runAction(SKAction.sequence([SKAction.scale(to: 1.5, duration:TimeInterval(0.1)), SKAction.scale(to: 1.0, duration:TimeInterval(0.1))]))
        } else {
            moving.speed = 0
            bird.physicsBody?.collisionBitMask = worldCategory
            bird.run(  SKAction.rotate(byAngle: CGFloat(Double.pi) * CGFloat(bird.position.y) * 0.01, duration:1), completion:{self.bird.speed = 0 })
            self.removeAction(forKey: "flash")
            self.run(SKAction.sequence([SKAction.repeat(SKAction.sequence([SKAction.run({
                self.backgroundColor = SKColor(red: 1, green: 0, blue: 0, alpha: 1.0)
                }),SKAction.wait(forDuration: TimeInterval(0.05)), SKAction.run({
                    self.backgroundColor = self.skyColor
                    }), SKAction.wait(forDuration: TimeInterval(0.05))]), count:4), SKAction.run({
                        self.canRestart = true
                        })]), withKey: "flash")
        }
    }
}

Swift Algorithm Club (binary search implementation):

public func binarySearch<T: Comparable>(_ a: [T], key: T) -> Int? {
    var lowerBound = 0
    var upperBound = a.count
    while lowerBound < upperBound {
        let midIndex = lowerBound + (upperBound - lowerBound) / 2
        if a[midIndex] == key {
            return midIndex
        } else if a[midIndex] < key {
            lowerBound = midIndex + 1
        } else {
            upperBound = midIndex
        }
    }
    return nil
}

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

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.

Code is compatible with Xcode 10 and Swift 4.2. We'll keep this updated with the latest version of Swift. If you're interested in a GitHub pages version of the repo, check out this.

:heart_eyes: Suggestions and contributions are welcome! :heart_eyes:

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.

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. A linear-time string algorithm that returns indexes of all occurrencies of a given pattern.
  • Rabin-Karp Faster search by using hashing.
  • 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:

Hybrid sorts:

Special-purpose sorts:

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

Compression

Miscellaneous

Mathematics

Machine learning

  • k-Means Clustering. Unsupervised classifier that partitions data into k clusters.
  • k-Nearest Neighbors
  • Linear Regression. A technique for creating a model of the relationship between two (or more) variable quantities.
  • Logistic Regression
  • Neural Networks
  • PageRank
  • Naive Bayes Classifier
  • Simulated annealing. Probabilistic technique for approximating the global maxima in a (often discrete) large search space.

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 probabilistic 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. A self balancing binary search tree.
  • Splay Tree. A self balancing binary search tree that enables fast retrieval of recently updated elements.
  • Threaded Binary Tree. A binary tree that maintains a few extra variables for cheap and fast in-order traversals.
  • Segment Tree. Can quickly compute a function over a portion of an array.
  • kd-Tree
  • Sparse Table. Another take on quickly computing a function over a portion of an array, but this time we'll make it even quicker!.
  • 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.
  • QuadTree. A tree with 4 children.
  • Octree. A tree with 8 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. A set where the number of times an element is added matters. (Also known as a bag.)
  • 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!

Like what you see? Check out Data Structures & Algorithms in Swift, the official book by the Swift Algorithm Club team!

Data Structures & Algorithms in Swift Book

You’ll start with the fundamental structures of linked lists, queues and stacks, and see how to implement them in a highly Swift-like way. Move on to working with various types of trees, including general purpose trees, binary trees, AVL trees, binary search trees, and tries.

Go beyond bubble and insertion sort with better-performing algorithms, including mergesort, radix sort, heap sort, and quicksort. Learn how to construct directed, non-directed and weighted graphs to represent many real-world models, and traverse graphs and trees efficiently with breadth-first, depth-first, Dijkstra’s and Prim’s algorithms to solve problems such as finding the shortest path or lowest cost in a network.

By the end of this book, you’ll have hands-on experience solving common issues with data structures and algorithms — and you’ll be well on your way to developing your own efficient and useful implementations!

You can find the book on the raywenderlich.com store.

Credits

The Swift Algorithm Club was originally created by Matthijs Hollemans.

It is now maintained by Vincent Ngo, Kelvin Lau, and Richard Ash.

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.

By posting here, or by submitting any pull request through this forum, you agree that all content you submit or create, both code and text, is subject to this license. Razeware, LLC, and others will have all the rights described in the license regarding this content. The precise terms of this license may be found here.

Build Status