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)")
2
Answers
You mean you need to sort the array in ascending order thats all
O/P:
EDIT 1:
As Leo pointed out in comments below, it makes absolute sense to use mutating function
sort
on this array to sort it in place instead of usingsorted(by:
which will create a new sorted array. Array is declared asvar
( You cant use mutating function likesort
on alet
). Hence updating the answer to reflect the sameIs this what you want
You can use the method
sorted(by:)
to create a sorted version of an array, orsort(by:)
to sort the array in place. (Both actually operate on objects that conform to theSequence
protocol. An array is conforms toSequence
.) Which version you use depends on your use-case.