Re: Mergesort not working

2019-12-29 Thread SimonN via Digitalmars-d-learn

On Sunday, 29 December 2019 at 11:02:34 UTC, Adnan wrote:

while (arr1_idx < arr1.length && arr2_idx < arr2.length)
result ~= arr1[arr1_idx] < arr2[arr2_idx] ? 
arr1[arr1_idx++] : arr2[arr2_idx++];


Given an array, it just returns a 1 length array. What's 
causing this?


This loop stops as soon as arr1 _or_ arr2 are exhausted. Then, 
merge() will wrongly discard the remainder of the array that is 
not yet exhausted.


The templating is good!

-- Simon


Mergesort not working

2019-12-29 Thread Adnan via Digitalmars-d-learn
This is not entirely a D question, but I'm not sure what about my 
mergesort implementation went wrong.


T[] merge(T)(T[] arr1, T[] arr2) {
T[] result;
result.reserve(arr1.length + arr2.length);

ulong arr1_idx = 0, arr2_idx = 0;
while (arr1_idx < arr1.length && arr2_idx < arr2.length)
result ~= arr1[arr1_idx] < arr2[arr2_idx] ? 
arr1[arr1_idx++] : arr2[arr2_idx++];

return result;
}

T[] sort(T)(T[] arr) {
return arr.length < 2 ? arr : merge(sort(arr[0 .. $ / 2]), 
sort(arr[$ / 2 .. $]));

}

Given an array, it just returns a 1 length array. What's causing 
this?