Example 1: merge sort iterative (string)
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]+" ");
}
}
Example 2: merge sort
function merge(list, start, midpoint, end) {
const left = list.slice(start, midpoint);
const right = list.slice(midpoint, end);
for (let topLeft = 0, topRight = 0, i = start; i < end; i += 1) {
if (topLeft >= left.length) {
list[i] = right[topRight++];
} else if (topRight >= right.length) {
list[i] = left[topLeft++];
} else if (left[topLeft] < right[topRight]) {
list[i] = left[topLeft++];
} else {
list[i] = right[topRight++];
}
}
}
function mergesort(list, start = 0, end = undefined) {
if (end === undefined) {
end = list.length;
}
if (end - start > 1) {
const midpoint = ((end + start) / 2) >> 0;
mergesort(list, start, midpoint);
mergesort(list, midpoint, end);
merge(list, start, midpoint, end);
}
return list;
}
mergesort([4, 7, 2, 6, 4, 1, 8, 3]);
Example 3: merge sort algorithm
#include <stdio.h>
void mergeSort(int a[], int p, int r)
{
int q;
if(p < r)
{
q = (p + r) / 2;
mergeSort(a, p, q);
mergeSort(a, q+1, r);
merge(a, p, q, r);
}
}
void merge(int a[], int p, int q, int r)
{
int b[5];
int i, j, k;
k = 0;
i = p;
j = q + 1;
while(i <= q && j <= r)
{
if(a[i] < a[j])
{
b[k++] = a[i++];
}
else
{
b[k++] = a[j++];
}
}
while(i <= q)
{
b[k++] = a[i++];
}
while(j <= r)
{
b[k++] = a[j++];
}
for(i=r; i >= p; i--)
{
a[i] = b[--k];
}
}
void printArray(int a[], int size)
{
int i;
for (i=0; i < size; i++)
{
printf("%d ", a[i]);
}
printf("\n");
}
int main()
{
int arr[] = {32, 45, 67, 2, 7};
int len = sizeof(arr)/sizeof(arr[0]);
printf("Given array: \n");
printArray(arr, len);
mergeSort(arr, 0, len - 1);
printf("\nSorted array: \n");
printArray(arr, len);
return 0;
}