been trying to program the following Quicksort Algorithm in Swift for a while now and cannot work out the issue. [Quicksort as there are around 15,000 actual values in array]. The problem is only the left half of the array is ordered (see pic), and the method is never exited (infinite loop). Following a Java conversion from http://www.java2novice.com/java-sorting-algorithms/quick-sort/ (tested in Java and does work). Cannot work out the error.
var arr = [Int]()
var length = 0
override func viewDidLoad()
{
super.viewDidLoad()
arr = [5,2,4,7,2,1,3,9,10,11,7,8]
print(arr)
sort(inputArr: &arr);
print(arr)
}
func sort(inputArr: inout [Int])
{
if (inputArr.count == 0) || (inputArr == nil)
{
print("finished")
return
}
arr = inputArr
length = arr.count
quicksort(low:0,high:length-1)
}
func quicksort(low: Int, high: Int)
{
var i = low
var j = high
var piv = (low + (high-low))
piv = piv / 2
let pivot_location = arr[piv]
print("----")
while i <= j
{
while arr[i] < pivot_location
{
i+=1
}
while arr[j] > pivot_location
{
j-=1
}
if i <= j
{
let temp = arr[i]
arr[i] = arr[j]
arr[j] = temp
i+=1
j-=1
}
}
print(arr)
if low < j
{
quicksort(low: low, high: j)
}
if i < high
{
quicksort(low: i, high: high)
}
}
Console print of array after iteration through method
Your computation of piv
and pivot_location
is wrong. It should be:
let piv = (low + (high - low) / 2)
let pivot_location = arr[piv]
Note that I moved the division by two inside the previous calculation.
Output:
[5, 2, 4, 7, 2, 1, 3, 9, 10, 11, 7, 8]
[1, 2, 4, 7, 2, 5, 3, 9, 10, 11, 7, 8]
[1, 2, 3, 2, 7, 5, 4, 9, 10, 11, 7, 8]
[1, 2, 2, 3, 7, 5, 4, 9, 10, 11, 7, 8]
[1, 2, 2, 3, 7, 5, 4, 9, 10, 11, 7, 8]
[1, 2, 2, 3, 7, 5, 4, 8, 7, 11, 10, 9]
[1, 2, 2, 3, 4, 5, 7, 8, 7, 11, 10, 9]
[1, 2, 2, 3, 4, 5, 7, 8, 7, 11, 10, 9]
[1, 2, 2, 3, 4, 5, 7, 8, 7, 11, 10, 9]
[1, 2, 2, 3, 4, 5, 7, 7, 8, 11, 10, 9]
[1, 2, 2, 3, 4, 5, 7, 7, 8, 9, 10, 11]
[1, 2, 2, 3, 4, 5, 7, 7, 8, 9, 10, 11]