10000 adds pancake sort algorithm · TheAlgorithms/Swift@3affd0b · GitHub
[go: up one dir, main page]

Skip to content

Commit 3affd0b

Browse files
committed
adds pancake sort algorithm
1 parent 7590755 commit 3affd0b

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed

DIRECTORY.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,7 @@
6161
* [Cocktailsort](https://github.com/TheAlgorithms/Swift/blob/master/sorts/CocktailSort.swift)
6262
* [Insertionsort](https://github.com/TheAlgorithms/Swift/blob/master/sorts/InsertionSort.swift)
6363
* [Mergesort](https://github.com/TheAlgorithms/Swift/blob/master/sorts/MergeSort.swift)
64+
* [Pancakesort](https://github.com/TheAlgorithms/Swift/blob/master/sorts/PancakeSort.swift)
6465
* [Quicksort](https://github.com/TheAlgorithms/Swift/blob/master/sorts/QuickSort.swift)
6566
* [Selectionsort](https://github.com/TheAlgorithms/Swift/blob/master/sorts/SelectionSort.swift)
6667

sorts/PancakeSort.swift

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
2+
/*
3+
Pancake sorting is the mathematical problem of sorting a disordered stack
4+
of pancakes in order of size when a spatula can be inserted at any
5+
point in the stack and used to flip all pancakes above it.
6+
*/
7+
8+
import Foundation
9+
10+
func flip(array: [Int], key: Int) -> [Int] {
11+
var flippedArray = array
12+
var pos = key
13+
var start = 0
14+
var aux = 0
15+
16+
while (start < pos) {
17+
aux = flippedArray[start]
18+
flippedArray[start] = flippedArray[pos]
19+
flippedArray[pos] = aux
20+
21+
start += 1
22+
pos -= 1
23+
}
24+
25+
return flippedArray
26+
}
27+
28+
func pancakeSort(_ array: [Int]) -> [Int] {
29+
var list = array
30+
var currentSize = list.count
31+
for _ in (1 ..< currentSize).reversed() {
32+
33+
let listToSearch = list[0...currentSize-1]
34+
let max = listToSearch.max() ?? 0
35+
let indexOfMax = listToSearch.firstIndex(of: max) ?? 0
36+
37+
if indexOfMax != currentSize - 1 {
38+
list = flip(array: list, key: indexOfMax)
39+
list = flip(array: list, key: currentSize - 1)
40+
}
41+
42+
currentSize -= 1
43+
}
44+
45+
return list
46+
}
47+
48+
// The code below can be used for testing
49+
//var numbers = [2, 4, 6, 12, 3, -2, 9, 14, 22, 0, 18]
50+
//numbers = pancakeSort(numbers)
51+
//print(numbers)

0 commit comments

Comments
 (0)
0