#VB.NET
I found this when I did your basic merge sort when I came across a StackOverFlowError. I was so confuzzled I asked a SO question about it. Without going to the link, can you find the cause? The link. Obviously this sorting algorithm uses recursion, but that is not the cause of the error being thrown.
Runner Class:
Module Module1
Sub Main()
dim array = new integer(100){}
dim random = new Random()
for i=0 to 100
array(i) = random.next()
next
dim sorter = new MergeSort()
sorter.sort(array)
End Sub
End Module
MergeSort Class:
public class MergeSort
private numbers() as integer
private helper() as integer
private number as integer
public sub sort(values as integer())
me.numbers = values
number = values.length
me.helper = new integer(number) {}
mergesort(0, number - 1)
end sub
private sub mergesort(low as integer, high as integer)
' check if low is smaller then high, if not then the array is sorted
if (low < high)
' Get the index of the element which is in the middle
dim middle as integer = low + (high - low) / 2
' Sort the left side of the array
mergesort(low, middle)
' Sort the right side of the array
mergesort(middle + 1, high)
' Combine them both
merge(low, middle, high)
end if
end sub
private sub merge(low as integer,middle as integer,high as integer)
' Copy both parts into the helper array
for l = low to high
helper(l) = numbers(l)
next
dim i as integer = low
dim j as integer = middle + 1
dim k as integer = low
' Copy the smallest values from either the left or the right side back
' to the original array
while (i <= middle andalso j <= high)
if (helper(i) <= helper(j))
numbers(k) = helper(i)
i+=1
else
numbers(k) = helper(j)
j+=1
end if
k+=1
end while
' Copy the rest of the left side of the array integero the target array
while (i <= middle)
numbers(k) = helper(i)
k+=1
i+=1
end while
end sub
end class