Skip to content

Instantly share code, notes, and snippets.

@ajjames
Created January 19, 2015 03:21
Show Gist options
  • Save ajjames/ec1ca09ba8bf80b689cf to your computer and use it in GitHub Desktop.
Save ajjames/ec1ca09ba8bf80b689cf to your computer and use it in GitHub Desktop.
Find 4 Largest
import UIKit
func find4Largest(numbers:[Int]) -> [Int]
{
let count = 4
assert(count < numbers.count, "Error: numbers must have at least \(count) elements")
if numbers.count < 2
{
return numbers
}
var results = [numbers[0],0,0,0]
for number in numbers
{
var newNumber = number
for var index = 0; index < count; ++index
{
let current = results[index]
if newNumber > current
{
results[index] = newNumber
newNumber = current
}
}
}
return results
}
/*
// uncomment this in a playground to see the demonstration
var array1 = [2,6,1,4,8,3,0,9,5,7]
find4Largest(array1)
var array2 = [Int]()
for _ in 0..<100
{
array2.append(Int(arc4random_uniform(1000)))
}
array2
find4Largest(array2)
*/
@ajjames
Copy link
Author

ajjames commented Jan 19, 2015

Copy and paste this into an iOS swift playground.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment