Merge Sort

·

1 min read

Merge sort follows divide and conquer approach for sorting.First we will divide the array then sort it and finally merge the array.Below is the code for merge sort. Copy and run this in java tutor site for better understanding.

TC - O(n log n)

SC- O(n)

import java.util.Arrays;

class Main {

public static void main(String[] args) {

int[] arr ={4,2,1,6,3,0}; arr=sort(arr);

System.out.println(Arrays.toString(arr));

}

static int[] sort(int[] arr){

if(arr.length==1){ return arr; }

int mid = arr.length/2;

int[] left = sort(Arrays.copyOfRange(arr, 0, mid));

int[] right = sort(Arrays.copyOfRange(arr, mid, arr.length));

return merge(left,right);

}

static int[] merge(int[] left ,int[] right){

int[] arr= new int[left.length+right.length];

int i=0;

int k=0;

int j=0;

while(i<left.length && j<right.length){

if(left[i]<=right[j]){

arr[k]=left[i];

i++;

}else{

arr[k]=right[j];

j++;

}

k++;

}

while(i<left.length){

arr[k]=left[i];

i++;

k++;

}

while(j<right.length){

arr[k]=right[j];

j++;

k++;

}

return arr;

} }