Reader small image

You're reading from  Swift Data Structure and Algorithms

Product typeBook
Published inNov 2016
Reading LevelIntermediate
PublisherPackt
ISBN-139781785884504
Edition1st Edition
Languages
Tools
Right arrow
Author (1)
Mario Eguiluz Alebicto
Mario Eguiluz Alebicto
author image
Mario Eguiluz Alebicto

Mario Eguiluz Alebicto is a software engineer with over 15 years of experience in development. He started developing software with Java, later switched to Objective-C when the first iPhone delighted the world, and now, he is working with Swift and involved in backend technologies. He loves to code, build exciting projects, and learn new languages and frameworks. Apart from software development, Mario loves to travel, learn new hobbies, practice sports, and considers himself a hardcore gamer, which he has been since he was a child.
Read more about Mario Eguiluz Alebicto

Right arrow

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 page is locked
Previous PageNext Page
You have been reading a chapter from
Swift Data Structure and Algorithms
Published in: Nov 2016Publisher: PacktISBN-13: 9781785884504

Author (1)

author image
Mario Eguiluz Alebicto

Mario Eguiluz Alebicto is a software engineer with over 15 years of experience in development. He started developing software with Java, later switched to Objective-C when the first iPhone delighted the world, and now, he is working with Swift and involved in backend technologies. He loves to code, build exciting projects, and learn new languages and frameworks. Apart from software development, Mario loves to travel, learn new hobbies, practice sports, and considers himself a hardcore gamer, which he has been since he was a child.
Read more about Mario Eguiluz Alebicto