Max Max - 5 months ago 31
Swift Question

Execution was interrupted, EXC Bad Instruction on func call with params - Swift iOS

Trying to do a binary search in swift , i am seeing the below exc bad instruction can any one please help what could be wrong in below code.

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

Answer

It's not in your call but in the implementation of your function.

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

must be

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

cause maxIndex is greater than midIndex-1