Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Swift Data Structure and Algorithms

You're reading from   Swift Data Structure and Algorithms Implement Swift structures and algorithms natively

Arrow left icon
Product type Paperback
Published in Nov 2016
Publisher Packt
ISBN-13 9781785884504
Length 286 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Author (1):
Arrow left icon
 Alebicto Alebicto
Author Profile Icon Alebicto
Alebicto
Arrow right icon
View More author details
Toc

Table of Contents (10) Chapters Close

Preface 1. Walking Across the Playground 2. Working with Commonly Used Data Structures FREE CHAPTER 3. Standing on the Shoulders of Giants 4. Sorting Algorithms 5. Seeing the Forest through the Tree 6. Advanced Searching Methods 7. Graph Algorithms 8. Performance and Algorithm Efficiency 9. Choosing the Perfect Algorithm

The insertion sort


The insertion sort is a simple and popular sorting algorithm. Since it has O(n2) average runtime it is very inefficient for sorting larger datasets. However, it is an algorithm of choice when the data is nearly sorted or when the dataset is small. Given those two conditions, it can potentially outperform sorting algorithms that are O(n log(n)) time complexity, such as merge sort.

The algorithm

The insertion sort algorithm performs in-place sorting and works with any element type that conforms to the comparable protocol. The element type must conform to comparable because we need to compare the individual elements against each other. It will make N-1 iterations, where i = 1 through N-1. The algorithm leverages the fact that elements 0 through i-1 have already been put in sorted order.

Let's look at the algorithm:

1  public func insertionSort<T: Comparable>(_ list: inout [T] ) { 
2      
3      if list.count <= 1 { 
4          return 
5      } &...
lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €18.99/month. Cancel anytime