0 < negative loop condition bug or misunderstanding on my part

ixid nuaccount at gmail.com
Tue Mar 6 21:11:18 PST 2012


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)
			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;
		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.


More information about the Digitalmars-d-learn mailing list