0

I know that there is a sort property in an array but i was trying to figure out how it was made.

var array = [3,6,9,2,1,5,7,4,8]

func sort() {

    for n in array {

        if n < array[array.indexOf(n)! + 1] {

            print("do nothing")


        } else  {

            array[n] = array[n + 1]
            array[n + 1] = array[n]
        }
    }


}

sort()
Luca Angeletti
  • 58,465
  • 13
  • 121
  • 148
Cyrus Ghiai
  • 291
  • 1
  • 3
  • 6
  • 2
    Most sorting implementations are complex. See https://github.com/jessesquires/swift-sorts for examples in Swift. – Eric Aya Jun 13 '16 at 13:08
  • 1
    1) "I get an error" is a pretty vague problem description. 2) Your code to swap two array elements does not work. 3) Use the *debugger* to isolate the problem. Hint: What happens for `n=9`? – Martin R Jun 13 '16 at 13:10
  • You can also take a look at the logic of some famous sorting alghoritms [here](https://en.wikipedia.org/wiki/Sorting_algorithm) – Luca Angeletti Jun 13 '16 at 13:11
  • Swift, specifically, uses of introsort (quicksort/heapsort) for all but smaller ranges, see [this source file from the Swift report](https://github.com/apple/swift/blob/master/stdlib/public/core/Sort.swift.gyb) as well as [this Q&A](https://stackoverflow.com/questions/27677026/swift-sorting-algorithm-implementation) for details. – dfrib Jun 13 '16 at 19:49

1 Answers1

1

You've got an index out of bounds error that comes from this line

if n < array[array.indexOf(n)! + 1] 

When n reaches the end of the array, you're trying to access the next element in the array, which doesn't exist because you've already reached the end.

You'll need to check to make sure that it is within the bounds of the array before you access the next element.

LuKenneth
  • 2,197
  • 2
  • 18
  • 41