skip to Main Content

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


  1. 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]

    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 using sorted(by: which will create a new sorted array. Array is declared as var ( You cant use mutating function like sort on a let). Hence updating the answer to reflect the same

            var arrio = [56, 78, 54, 91]
            arrio.sort()
            debugPrint(arrio)
    

    Is this what you want

    Login or Signup to reply.
  2. You can use the method sorted(by:) to create a sorted version of an array, or sort(by:) to sort the array in place. (Both actually operate on objects that conform to the Sequence protocol. An array is conforms to Sequence.) Which version you use depends on your use-case.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search