a recursive function that sorts a sequence of numbers in ascending order using the merge function above. code example
Example 1: Merge Sort python
def merge_sort(arr):
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left, right = merge_sort(arr[:mid]), merge_sort(arr[mid:])
return merge(left, right, arr.copy())
def merge(left, right, merged):
left_cursor, right_cursor = 0, 0
while left_cursor < len(left) and right_cursor < len(right):
if left[left_cursor] <= right[right_cursor]:
merged[left_cursor+right_cursor]=left[left_cursor]
left_cursor += 1
else:
merged[left_cursor + right_cursor] = right[right_cursor]
right_cursor += 1
for left_cursor in range(left_cursor, len(left)):
merged[left_cursor + right_cursor] = left[left_cursor]
for right_cursor in range(right_cursor, len(right)):
merged[left_cursor + right_cursor] = right[right_cursor]
return merged
Example 2: merge sort iterative (string)
//Joshua Khumalo
import java.util.Arrays;
public class Demo{
public static void merge_sort(int[] my_arr){
if(my_arr == null){
return;
}
if(my_arr.length > 1){
int mid = my_arr.length / 2;
int[] left = new int[mid];
for(int i = 0; i < mid; i++){
left[i] = my_arr[i];
}
int[] right = new int[my_arr.length - mid];
for(int i = mid; i < my_arr.length; i++){
right[i - mid] = my_arr[i];
}
merge_sort(left);
merge_sort(right);
int i = 0;
int j = 0;
int k = 0;
while(i < left.length && j < right.length){
if(left[i] < right[j]){
my_arr[k] = left[i];
i++;
} else {
my_arr[k] = right[j];
j++;
}
k++;
}
while(i < left.length){
my_arr[k] = left[i];
i++;
k++;
}
while(j < right.length){
my_arr[k] = right[j];
j++;
k++;
}
}
}
public static void main(String[] args){
int my_arr[] = {56, 78, 91, 21, 34, 0, 11};
int i=0;
merge_sort(my_arr);
System.out.println("The array after sorting is ");
for(i=0; i<my_arr.length; i++)
System.out.print(my_arr[i]+" ");
}
}