Last active
April 18, 2016 07:13
-
-
Save mhlangagc/f4d6858b6770aebafd78195a9ee57398 to your computer and use it in GitHub Desktop.
Implementation of a quick Sort algorithm in swift
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 UIKit | |
//Random Interger Generator :: You could alternatively create your own array of Intergers. I prefer a a random way to my array length, minumum and maximum elements. | |
func randomIntergerInRange(low:Int, high:Int) -> Int { | |
let randomGeneratedNumber = low + Int(arc4random()) % (high - low); | |
return Int(randomGeneratedNumber) | |
} | |
/* | |
Length : Number of elements in the Array | |
Min : Lowest Value in the Array | |
Max : Highest Interger in the array | |
*/ | |
func randomNumberArray(length: Int, min: Int, max: Int) -> [Int] { | |
// Create an Array of random Intergers from different Elements | |
var randomArray = [Int]() | |
for _ in 0..<length { | |
randomArray.append(randomIntergerInRange(min, high: max)) | |
} | |
return randomArray | |
} | |
//Sorting Algorithm | |
func quickSortAlgorithm(createRandomArray: [Int])->Array<Int> { | |
var leftSide = [Int]() //Lower than the Pivot | |
var rightSide = [Int]() //Greater than the Pivot | |
var equal = [Int]() //Equal to the Pivot | |
//Sort the Random Arrat | |
if createRandomArray.count > 1{ | |
let pivot = createRandomArray[0] | |
for x in createRandomArray { | |
if x < pivot{ | |
leftSide.append(x) | |
} | |
if x == pivot { | |
equal.append(x) | |
} | |
if x > pivot { | |
rightSide.append(x) | |
} | |
} | |
return (quickSortAlgorithm(leftSide)+equal+quickSortAlgorithm(rightSide)) //Use Recursion to repeat the process for left & Right Side | |
} | |
else { | |
return createRandomArray | |
} | |
} | |
//Run the algorithm on the random Number Array with your own array length, Min number and Max Number | |
quickSortAlgorithm(randomNumberArray(10, min: 0, max: 100)) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment