Skip to content

Implemented Shell sort as Array extension #1

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 6, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions Sort.playground/Pages/Shell.xcplaygroundpage/Contents.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
//: [Previous](@previous)

import Foundation

// Shell sort is an improved version of insertion sort. The original list is broken into smaller sublists and then individually sorted using insertion sort.

extension Array where Element: Comparable {

public mutating func shellSorted(order sign: (Element, Element) -> Bool) {
var subcount = self.count / 2

while subcount > 0 {
for i in 0..<self.count {
let temp = self[i]
var j = i

while j >= subcount && sign(self[j - subcount], temp) {
self[j] = self[j - subcount]
j -= subcount
}
self[j] = temp
}
subcount /= 2
}

}
}

//: Usage

var data = [4, 1, 5, 6, 1, 2, 9, 8, 5, 4, 2, 7, 6]
data.shellSorted(order: >)

//: [Next](@next)
1 change: 1 addition & 0 deletions Sort.playground/contents.xcplayground
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,6 @@
<page name='Quick-Hoare-Scheme'/>
<page name='Quick-Lomuto-Scheme'/>
<page name='Bubble'/>
<page name='Shell'/>
</pages>
</playground>