How to arrange an array in a way better than this in Swift? I'm sure there is an easier and shorter way to do it?! I've used for loop and if conditions, then I've assigned the smallest ones in separate array. I think this can be done with one single array feature..
How to sort an array of numbers in order?
var sortarray = [0, 0, 0, 0]
var arrio = [56, 78, 54, 91]
var smallestNumber = 0
var indexNumber = 0
print("unorder array was: \(arrio)")
for i in 0...3 {
if arrio[0] < arrio[1] {
smallestNumber = arrio[0]
indexNumber = 0
} else {
smallestNumber = arrio[1]
indexNumber = 1
}
if smallestNumber >= arrio[2] {
smallestNumber = arrio[2]
indexNumber = 2
}
if smallestNumber >= arrio[3] {
smallestNumber = arrio[3]
indexNumber = 3
}
sortarray[i] = smallestNumber
arrio[indexNumber] = 1000000
}
print("array after sorting from smaller to bigger has become: \(sortarray)")
CodePudding user response:
You mean you need to sort the array in ascending order thats all
var arrio = [56, 78, 54, 91]
arrio = arrio.sorted(by: < )
debugPrint(arrio)
O/P:
[54, 56, 78, 91]
Is this what you want