Last active
November 21, 2020 06:43
-
-
Save thatswiftguy/f619803efcbe24e9194723801114754a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
``` | |
import Foundation | |
struct mySortedArray<T: Comparable> { | |
// We are Creating an Array and intialise it | |
var array = [T]() | |
init(array: [T]) { | |
self.array = array.sorted() | |
} | |
// Here are some Computed varibales | |
var isEmpty: Bool { | |
return array.isEmpty | |
} | |
var count: Int { | |
return array.count | |
} | |
subscript(index: Int) -> T { | |
return array[index] | |
} | |
// Since we are mutating the array , we must create mutating type of fucntion here | |
mutating func removeAtIndex(index: Int) -> T { | |
return array.remove(at: index) | |
} | |
mutating func removeAll() { | |
array.removeAll() | |
} | |
// To insert , we can find the correct location by linear and binary search , so we are using binary to be effecent | |
mutating func insert(_ newElement: T) -> Int { | |
let i = findPositionBinarySearch(newElement) | |
array.insert(newElement, at: i) | |
return i | |
} | |
func findPositionLinearly(_ newElement: T) -> Int { | |
for i in 0..<array.count { | |
if newElement <= array[i] { | |
return i | |
} | |
} | |
return array.count | |
} | |
func findPositionBinarySearch(_ newElement: T) -> Int { | |
var start = 0 | |
var end = array.count | |
while start < end { | |
let mid = start + (end - start) / 2 | |
if array[mid] == newElement { | |
return mid | |
} else if array[mid] < newElement { | |
start = mid + 1 | |
} else { | |
end = mid | |
} | |
} | |
return start | |
} | |
} | |
// We want our strings to be sorted | |
extension mySortedArray: CustomStringConvertible { | |
public var description: String { | |
return array.description | |
} | |
} | |
var integerExample = mySortedArray<Int>(array: [2,8,6,9,-7,-1,0,0]) | |
var stringExample = mySortedArray<String>(array:["cat","bat","tom"]) | |
print(integerExample) // [-7,-1,0,0,2,6,8,9] | |
print(stringExample) // ["bat","cat","tom"] | |
integerExample.insert(0) | |
stringExample.insert("hello") | |
print(integerExample) // [-7,-1,0,0,0,2,6,8,9] | |
print(stringExample) // ["bat","cat","hello","tom"] | |
``` |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment