merge sort is also called as code example
Example 1: 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
Example 2: merge sort algo
def mergeSort(arr):
if len(arr) >1:
mid = len(arr)//2 # Finding the mid of the array
L = arr[:mid] # Dividing the array elements
R = arr[mid:] # into 2 halves
mergeSort(L) # Sorting the first half
mergeSort(R) # Sorting the second half
i = j = k = 0
# Copy data to temp arrays L[] and R[]
while i < len(L) and j < len(R):
if L[i] < R[j]:
arr[k] = L[i]
i+= 1
else:
arr[k] = R[j]
j+= 1
k+= 1
# Checking if any element was left
while i < len(L):
arr[k] = L[i]
i+= 1
k+= 1
while j < len(R):
arr[k] = R[j]
j+= 1
k+= 1
# Code to print the list
def printList(arr):
for i in range(len(arr)):
print(arr[i], end =" ")
print()
# driver code to test the above code
if __name__ == '__main__':
arr = [12, 11, 13, 5, 6, 7]
print ("Given array is", end ="\n")
printList(arr)
mergeSort(arr)
print("Sorted array is: ", end ="\n")
printList(arr)