Write a program to sort an array. Use of merge sort.
Example 1:
Input :arr[]={3,1,4,12,5,13,6}
Output: 1 3 4 5 6 12 13
Approach
Java
import java.util.Arrays;public class MergeSort {public static void main(String[] args) {int arr[] = { 3, 1, 4, 12, 5, 13, 6 };int n = arr.length;int aux[] = new int[n];mergeSort(arr, aux, 0, n - 1);System.out.println("Sorted array is" + Arrays.toString(arr));}// method for merge sortstatic void mergeSort(int arr[], int aux[], int low, int high) {// base caseif (high <= low)return;int mid = low + (high - low) / 2;// left subarraymergeSort(arr, aux, low, mid);// right subarraymergeSort(arr, aux, mid + 1, high);// merge two sortd arraymergeTwoSortedArray(arr, aux, low, mid, high);}static void mergeTwoSortedArray(int arr[], int aux[],int low, int mid, int high) {int k = low, i = low, j = mid + 1;while (i <= mid && j <= high) {// if right subarray value is greater// the insert the left subarray into// the resultif (arr[i] < arr[j]) {aux[k++] = arr[i];i++;}// otherwise insert the right subarray value// into the resultelse {aux[k++] = arr[j];j++;}}// if left subarray is remaining and right subaray is// overwhile (i <= mid)aux[k++] = arr[i++];// if right subarray is remaining and left subarray is// overwhile (j <= high)aux[k++] = arr[j++];// store result back to original arrayfor (int l = low; l <= high; l++)arr[l] = aux[l];}}//Time Complexity:O(nlog(n))//Space Complexity:O(n)
C++
#include <bits/stdc++.h>using namespace std;//function to merge two//sorted arrayvoid mergeTwoSortedArray(int arr[],int aux[],int low,int mid,int high){int k=low,i=low,j=mid+1;while(i<=mid&&j<=high){//if right subarray value is greater//the insert the left subarray into//the resultif(arr[i]<arr[j]){aux[k++]=arr[i];i++;}//otherwise insert the right subarray value//into the resultelse{aux[k++]=arr[j];j++;}}//if left subarray is remaining and right subaray is//overwhile(i<=mid)aux[k++]=arr[i++];//if right subarray is remaining and left subarray is//overwhile(j<=high)aux[k++]=arr[j++];//store result back to original arrayfor(int i=low;i<=high;i++)arr[i]=aux[i];}//funtion for merge sortvoid mergeSort(int arr[],int aux[],int low,int high){//base caseif(high<=low)return;int mid=low+(high-low)/2;//left subarraymergeSort(arr,aux,low,mid);//right subarraymergeSort(arr,aux,mid+1,high);//merge two sortd arraymergeTwoSortedArray(arr,aux,low,mid,high);}int main(){int arr[]={3,1,4,12,5,13,6};int n=sizeof(arr)/sizeof(arr[0]);int aux[n];mergeSort(arr,aux,0,n-1);cout<<"Sorted array is\n";for(int i=0;i<n;i++)cout<<arr[i]<<" ";return 0;}//Time Complexity:O(nlog(n))//Space Complexity:O(n)
No comments:
Post a Comment