a year ago,I'm here git onReleased aSwift used to achieve stack,There are two versions。Because Swift itself does not achieve this thing - even though the official part of the tutorial is to use genericsThe StackExamples cited。
Perhaps people think this is too simple, right
In short,This time I play this thing,Because the HMM Viterbi algorithm needs to be done to trim,Otherwise, the path too much unnecessarily increase the amount of calculation - after all,,We are concerned first,Who would pay attention to second it?
所以,This stack is based on the native Array。A few of the ideas and the same common stack,But this time we use the structure to do。
In Swift background,In fact, not particularly rigorous for the structure and class distinction,Only time will really need to distinguish between different behaviors。Here are optimized background Swift。
First we first put a common stack:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
struct PriorityStack<Element> { fileprivate var items:[Element] = [] let maxLength:Int init(Length length:Int) {//长度固定,这样栈才能把小的元素自动丢弃 maxLength = length } mutating func push(_ newElement:Element) { } mutating func pop()->Element? { guard count > 0 else {return nil} return items.removeFirst() } func empty() -> Bool { return items.isEmpty } func peek() ->Element? { return items.last } var count:Int { return items.count } } |
There is not any difference,Right? First of all,We want to compare elements,after all,You want to give them the sort:
1 |
struct PriorityStack<Element:Comparable> { |
So we let the generic is defined as follows Comparable type。
Then there is the stack of the process,Here we learn from the quick sort and insertion sort algorithm (actually my own sorting algorithm design,I later learned that there are special sorting algorithm,And a variety of development seems to be a compulsory content of the interview ......?♂️)
In short,I re-invent the wheel again,Too embarrassed to say that my own design algorithm,I had to say draws ......
General process
1、We first determine that the stack is not full,If the full and new element is smaller than the smallest,Then discard:
1 2 3 |
if maxLength == count && newElement < items.last! { return } |
2、If the stack is empty,Then added directly:
1 |
if items.isEmpty {items.append(newElement);return} |
3、This time interesting,We use binary thinking (in fact, the fast row block),Existing data from the middle of the array if the number of relatively large then it started to go up than the middle value,If small to go down,Until you find the proper position and insert their own:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
var middleIndex = Int(count/2) if newElement > items[middleIndex] { while middleIndex >= 0 { if newElement > items[middleIndex] { if middleIndex == 0 {items.insert(newElement, at: 0)} middleIndex -= 1 continue } items.insert(newElement, at: middleIndex + 1) break } } else { while middleIndex < count { if newElement < items[middleIndex] { if middleIndex == count - 1 {items.append(newElement)} middleIndex += 1 continue } items.insert(newElement, at: middleIndex) break } } |
4、At last,If the length of the stack (here, perhaps we should say the height),In short,If the length is equal to the value we set,This time it inserted a valid (that is more than the minimum stack inside bigger) value,Then the length of the stack to overflow 1,Then:
1 |
if count > maxLength {items.removeLast()} |
Such,Internal stack items It is automatically sorted it!
then,In case you've read,I'll last a flowchart:
of course,It may not be very easy to use,After all, sometimes we have to get this stack list,所以,Follow it Sequence It is necessary。
Sequence
This is an agreement in Swift,All follow its type can be for-in Traversed,of course,For example, there is a corresponding map Such methods will automatically have,In simple terms it is that you can treat it as a Array to treat it!
Then,How to do it? If you point to open Sequence,You will find way too many statements - in fact do not need to implement all,Because Swift have to help you achieve better,You need to do is to achieve both:
1 2 |
typealias Iterator func makeIterator() -> PriorityStack.Iterator |
Its that simple!
but,In fact, it is difficult to,Because there might be a little wound,That is because we do not have to traverse itself,But to traverse the stack inside Array,It is simple to implement but the idea is not the same and direct realization Sequence。
First of all,You do not need to follow to achieve a IteratorProtocol The walker,Because our infrastructure is an array,It will have its own is not it?
Secondly,You do not need to implement makeIterator() ,Reason Same as above。
所以,Our opening array makeIterator() ,You can see it returns a IndexingIterator<Array<Element>> ,And then point to go see this is a structure - in short,Do not ignore it,As long as we have the return type just fine,then makeIterator() Returns the underlying array itself makeIterator() .,所以,In fact, the code is this:
1 2 3 4 5 6 |
extension PriorityStack:Sequence { typealias Iterator = IndexingIterator<Array<Element>> func makeIterator() -> PriorityStack.Iterator { return items.makeIterator() } } |
This time,When you PriorityStack Do any traversal operation,It has done the equivalent of its internal array - no additional write a getter operation to remove the array again。
Then,For chestnuts:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
var pStack:PriorityStack<Int> = PriorityStack(Length: 5) pStack.push(1) pStack.push(5) pStack.push(2) pStack.push(8) pStack.push(100) pStack.push(999999) pStack.push(0) print(pStack.maxLength) print("---") for item in pStack { print(item) } let list:[Int] = pStack.map{return $0} print(list) |
and then?
All right,This summary on here,I have put myStack-in-Swiftupdated,Inside joined the automatic sorting stack,You can go to download it and then take a look at the complete code。
Other than that,If you want to learn fast row,We can see here:http://bubkoo.com/2014/01/12/sort-algorithm/quick-sort/
There Insertion Sort:https://zh.wikipedia.org/zh-hans/插入排序
Original article written by LogStudio:R0uter's Blog » A stack automatically sorted Swift
Reproduced Please keep the source and description link:https://www.logcg.com/archives/2530.html