Alternative Sorting of Array in Swift
1 min readNov 23, 2020
var array = [7, 1, 2, 3, 4, 5, 6]
Output would be like this 7 1 6 2 5 3 4
Main Ideas-
- First we sort the array using .sorted() function in Swift
- We maintain two pointers, one from beginning and one from end in sorted array. We alternatively print elements pointed by two pointers and move them toward each other.
class ViewController: UIViewController {
var array = [7, 1, 2, 3, 4, 5, 6]
//oup
//[7,1,6,2,5,3,4]
override func viewDidLoad() {
super.viewDidLoad()
let sortedArray = array.sorted()
sorted(array: sortedArray, n: sortedArray.count)
// Do any additional setup after loading the view.
}
func sorted (array:Array<Any>,n:Int){
var i = 0;
var j = n-1;
while (i < j){
print(array[j])
print(array[i])
j -= 1;
i += 1;
}
if (n % 2 != 0){
print(array[i])
}
}
}
output -
7
1
6
2
5
3
4