On 03/06/2012 09:11 PM, ixid wrote:
> I'm writing my first basic algorithms, this one is merge sort. This
> version throws an exception when array.length - setSize is negative
> (which should be fine, the rest of my function would deal with it):
>
> template mergeSort(T)
> {
> void mergeSort(ref T[] array, const T setSize = 100)
> {
> T[][] merge;
> merge.length = array.length / setSize;
> T ii, jj;
> for(ii = 0, jj = 0;ii < array.length - setSize;ii += setSize, ++jj)

We don't know what T is, but I assume a signed type like int.

array.length is size_t, i.e. an unsigned type. Unsigned types have this nasty habit of converting the entire expression to unsigned (that is a rule since C). So array.length - setSize above is size_t.

In other words, it is never negative.

> merge[jj] = array[ii..ii + setSize];
>
> ...
>
> If I make the seemingly pointless change to this:
>
> template mergeSort(T)
> {
> void mergeSort(ref T[] array, const T setSize = 100)
> {
> T[][] merge;
> merge.length = array.length / setSize;
> T ii, jj;
> T temp2 = array.length - setSize;

There, you are setting temp2's size to be T (e.g. int), so temp2 can be negative.

> for(ii = 0, jj = 0;ii < temp2;ii += setSize, ++jj)
> merge[jj] = array[ii..ii + setSize];
>
> Where it's a temporary variable then it works perfectly well.

Ali

Reply via email to