Book Image

Swift Data Structure and Algorithms

By : Mario Eguiluz Alebicto
Book Image

Swift Data Structure and Algorithms

By: Mario Eguiluz Alebicto

Overview of this book

Apple’s Swift language has expressive features that are familiar to those working with modern functional languages, but also provides backward support for Objective-C and Apple’s legacy frameworks. These features are attracting many new developers to start creating applications for OS X and iOS using Swift. Designing an application to scale while processing large amounts of data or provide fast and efficient searching can be complex, especially running on mobile devices with limited memory and bandwidth. Learning about best practices and knowing how to select the best data structure and algorithm in Swift is crucial to the success of your application and will help ensure your application is a success. That’s what this book will teach you. Starting at the beginning, this book will cover the basic data structures and Swift types, and introduce asymptotic analysis. You’ll learn about the standard library collections and bridging between Swift and Objective-C collections. You will see how to implement advanced data structures, sort algorithms, work with trees, advanced searching methods, use graphs, and performance and algorithm efficiency. You’ll also see how to choose the perfect algorithm for your problem.
Table of Contents (15 chapters)
Swift Data Structure and Algorithms
Credits
About the Authors
About the Reviewers
www.PacktPub.com
Preface

Depth first search


When we have a graph (such as a tree or a binary tree) with information, it is very useful (and common) in the real world to visit the vertices/nodes of the graph looking for some info.

Depth First Search (DFS) is one of the most famous techniques to do this. This type of traversal visits nodes from top to bottom with only one condition: when visiting a node, you must visit the first (left) child of it, then the node itself, then the following child (to the right). Let's see an example with a binary search tree (which is a graph). Remember that a binary search tree is an ordered tree in which each node has at most two children.

Take a look at the following example:

DFS example

Try to apply this recursive pseudocode to the previous figure (in your mind), starting from the root node:

public func depthFirstSearch(node:TreeNode) {
    depthFirstSearch(node.leftChild)
    print(node.value)
    depthFirstSearch(node.rightChild)
}

As you can see, we have a binary...