Alternative Sorting of Array in Swift

Varun Singhal
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-

  1. First we sort the array using .sorted() function in Swift
  2. 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

--

--

Varun Singhal
Varun Singhal

Written by Varun Singhal

React Native/iOS Developer (Mobile App Developer)

No responses yet