Created
January 19, 2015 03:21
-
-
Save ajjames/ec1ca09ba8bf80b689cf to your computer and use it in GitHub Desktop.
Find 4 Largest
This file contains 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 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) | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Copy and paste this into an iOS swift playground.