尝试快速执行二进制搜索,我看到以下排除错误的指令可以帮助任何人帮助以下代码中的错误。

import UIKit

let numberList : Array<Int> = [1,3,4,6,7,10,12,14,17,18,20,23,25,55,56,60,67]

numberList.count

/* Binary Search */

func binarySearch(sequence:Array<Int>,key:Int) -> Int{

  //get first index, Mid index and Max index of array
  //start index would be zero

  var startIndex = 0
  var midIndex = (startIndex + sequence.count) / 2
  var maxIndex = sequence.count-1

  print(midIndex)

  if key > numberList[midIndex] {

    print("key found after midIndex")

  }

  if key < numberList[midIndex] {

    print("key found before midIndex")
    var slice = Array(sequence[maxIndex...midIndex-1])
    print(slice)
    //binarySearch(sequence,key)

  }

  return key
}

//binarySearch(numberList, key: 10)
binarySearch(numberList, key: 10) //error on this line :- exc bad instruction

最佳答案

它不在您的调用中,而是在函数的实现中。

var slice = Array(sequence[maxIndex...midIndex-1])


一定是

var slice = Array(sequence[midIndex-1...maxIndex])


因为maxIndex大于midIndex-1

关于swift - 执行被中断,带有参数的func调用上的EXC错误指令-Swift iOS,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37786934/

10-12 14:39