www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Mergesort not working

reply Adnan <contact.adnan.02 protonmail.com> writes:
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?
Dec 29 2019
parent SimonN <eiderdaus gmail.com> writes:
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
Dec 29 2019