Skip to content

[Swift 4] Update Shell Sort #606

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 2 commits into from
Sep 11, 2017
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
18 changes: 2 additions & 16 deletions Shell Sort/README.markdown
Original file line number Diff line number Diff line change
Expand Up @@ -117,24 +117,10 @@ Here is an implementation of Shell Sort in Swift:
var arr = [64, 20, 50, 33, 72, 10, 23, -1, 4, 5]

public func shellSort(_ list: inout [Int]) {

var sublistCount = list.count / 2

while sublistCount > 0 {

for index in 0..<list.count {

guard index + sublistCount < list.count else { break }

if list[index] > list[index + sublistCount] {
swap(&list[index], &list[index + sublistCount])
}

guard sublistCount == 1 && index > 0 else { continue }

if list[index - 1] > list[index] {
swap(&list[index - 1], &list[index])
}
for pos in 0..<sublistCount {
insertionSort(&list, start: pos, gap: sublistCount)
}
sublistCount = sublistCount / 2
}
Expand Down
34 changes: 34 additions & 0 deletions Shell Sort/Shell Sort.playground/Contents.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
//: Playground - noun: a place where people can play

import UIKit

// last checked with Xcode 9.0b4
#if swift(>=4.0)
print("Hello, Swift 4!")
#endif

public func insertionSort(_ list: inout [Int], start: Int, gap: Int) {
for i in stride(from: (start + gap), to: list.count, by: gap) {
let currentValue = list[i]
var pos = i
while pos >= gap && list[pos - gap] > currentValue {
list[pos] = list[pos - gap]
pos -= gap
}
list[pos] = currentValue
}
}

public func shellSort(_ list: inout [Int]) {
var sublistCount = list.count / 2
while sublistCount > 0 {
for pos in 0..<sublistCount {
insertionSort(&list, start: pos, gap: sublistCount)
}
sublistCount = sublistCount / 2
}
}

var arr = [64, 20, 50, 33, 72, 10, 23, -1, 4, 5]

shellSort(&arr)
4 changes: 4 additions & 0 deletions Shell Sort/Shell Sort.playground/contents.xcplayground
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<playground version='5.0' target-platform='ios'>
<timeline fileName='timeline.xctimeline'/>
</playground>