Skip to content

Instantly share code, notes, and snippets.

View ChenCodes's full-sized avatar
:electron:
writing that react code

Jack Chen ChenCodes

:electron:
writing that react code
  • East Palo Alto, CA
View GitHub Profile
//iterative
func binarySearch<T: Comparable>(_ a: [T], key: T) -> Int? {
var lowerBound = 0
var upperBound = a.count
while lowerBound < upperBound {
let midIndex = lowerBound + (upperBound - lowerBound) / 2
if a[midIndex] == key {
return midIndex
} else if a[midIndex] < key {
lowerBound = midIndex + 1
public class BinarySearchTree<T: Comparable> {
private(set) public var value: T
private(set) public var parent: BinarySearchTree?
private(set) public var left: BinarySearchTree?
private(set) public var right: BinarySearchTree?
public init(value: T) {
self.value = value
}
var randomNumbers = [5, 4, 3, 2, 1]
func selectionSort(nums: inout [Int]) -> [Int] {
// index of element we're trying to put in the leftmost position
for i in 0..<nums.count - 1 {
// set our smallest element to be the current index's element
var smallestElement = nums[i]
// set our smallest index to be the current index's element
@ChenCodes
ChenCodes / bubbleSort.swift
Last active January 2, 2017 03:13
Bubblesort runtime is n^2 for average and worst case scenario. Memory usage is constant.
func bubbleSort(nums: inout [Int]) -> [Int] {
while true {
var swapped = false
for i in 0..<nums.count - 1 {
if nums[i] > nums[i + 1] {
let temp = nums[i]
nums[i] = nums[i + 1]
nums[i + 1] = temp
@ChenCodes
ChenCodes / gist:e45bd03a216c214ba310b1164d74ae79
Created December 27, 2016 21:43
background_thread.swift
// Without threading
func slow() {
let methodStart = Date()
let url = URL(string: "some string url goes here for an image")
do {
let data = try Data(contentsOf: url!)
self.imageView.image = UIImage(data: data)
} catch {
print("error"
@ChenCodes
ChenCodes / closures.swift
Created December 27, 2016 20:46
Closures in Swift
var noParametersOrReturn: () -> () = {
print("I have no parameters or return values, so I print"
}
// noParametersOrReturn()
var noParameterAndOneReturn: () -> String = {
return "I am a string"
}