From d28e5a4cb8da650f81ac115a41820170cc111d4a Mon Sep 17 00:00:00 2001 From: Bartosz Nowak Date: Fri, 29 Dec 2023 13:15:22 +0100 Subject: [PATCH] merge iterative 8% speed improvement --- src/common/merge_sort.cairo | 68 +++++++++++++++++++------------------ 1 file changed, 35 insertions(+), 33 deletions(-) diff --git a/src/common/merge_sort.cairo b/src/common/merge_sort.cairo index 72e05f709..0d2758e70 100644 --- a/src/common/merge_sort.cairo +++ b/src/common/merge_sort.cairo @@ -19,45 +19,47 @@ fn merge_sort, +Drop, +PartialOrd>(arr: Array) -> Array let sorted_right = merge_sort(right_arr); let mut result_arr = array![]; - merge_recursive(sorted_left, sorted_right, ref result_arr, 0, 0); + merge_iterative(sorted_left.span(), sorted_right.span(), ref result_arr); result_arr } -// Merge two sorted arrays -/// # Arguments -/// * `left_arr` - Left array -/// * `right_arr` - Right array -/// * `result_arr` - Result array -/// * `left_arr_ix` - Left array index -/// * `right_arr_ix` - Right array index -/// # Returns -/// * `Array` - Sorted array -fn merge_recursive, +Drop, +PartialOrd>( - left_arr: Array, - right_arr: Array, - ref result_arr: Array, - left_arr_ix: u32, - right_arr_ix: u32 +fn merge_iterative, +Drop, +PartialOrd>( + left_arr: Span, right_arr: Span, ref result_arr: Array, ) { - if result_arr.len() == left_arr.len() + right_arr.len() { - return; - } + let mut left_arr_ix = 0; + let mut right_arr_ix = 0; - if left_arr_ix == left_arr.len() { - result_arr.append(*right_arr[right_arr_ix]); - return merge_recursive(left_arr, right_arr, ref result_arr, left_arr_ix, right_arr_ix + 1); - } + loop { + if left_arr_ix < left_arr.len() && right_arr_ix < right_arr.len() { + if *left_arr.at(left_arr_ix) < *right_arr.at(right_arr_ix) { + result_arr.append(*left_arr.at(left_arr_ix)); + left_arr_ix += 1; + } else { + result_arr.append(*right_arr.at(right_arr_ix)); + right_arr_ix += 1; + } + } else { + break; + } + }; - if right_arr_ix == right_arr.len() { - result_arr.append(*left_arr[left_arr_ix]); - return merge_recursive(left_arr, right_arr, ref result_arr, left_arr_ix + 1, right_arr_ix); - } + // Append the remaining elements from left_arr, if any + loop { + if left_arr_ix < left_arr.len() { + result_arr.append(*left_arr.at(left_arr_ix)); + left_arr_ix += 1; + } else { + break; + } + }; - if *left_arr[left_arr_ix] < *right_arr[right_arr_ix] { - result_arr.append(*left_arr[left_arr_ix]); - merge_recursive(left_arr, right_arr, ref result_arr, left_arr_ix + 1, right_arr_ix) - } else { - result_arr.append(*right_arr[right_arr_ix]); - merge_recursive(left_arr, right_arr, ref result_arr, left_arr_ix, right_arr_ix + 1) + // Append the remaining elements from right_arr, if any + loop { + if right_arr_ix < right_arr.len() { + result_arr.append(*right_arr.at(right_arr_ix)); + right_arr_ix += 1; + } else { + break; + } } }