importjava.io.BufferedReader;importjava.io.InputStreamReader;importjava.util.Arrays;publicclassMergeSort{// Function to merge the two sorted arraysstaticvoidmerge(int[]array,intlow,intmid,inthigh){inti,j,k;int[]c=newint[high-low+1];k=0;i=low;j=mid+1;while(i<=mid&&j<=high){if(array[i]<=array[j]){c[k++]=array[i++];}else{c[k++]=array[j++];}}while(i<=mid){c[k++]=array[i++];}while(j<=high){c[k++]=array[j++];}k=0;for(i=low;i<=high;i++){array[i]=c[k++];}}// Function implementing the merge sortstaticvoidmergeSort(int[]array,intlow,inthigh){if(high-low+1>1){intmid=(low+high)/2;mergeSort(array,low,mid);mergeSort(array,mid+1,high);merge(array,low,mid,high);}}// Function to read the input and display the outputpublicstaticvoidmain(String[]args){BufferedReaderbr=newBufferedReader(newInputStreamReader(System.in));intsize;System.out.println("Enter the size of the array");try{size=Integer.parseInt(br.readLine());}catch(Exceptione){System.out.println("Invalid Input");return;}int[]array=newint[size];System.out.println("Enter array elements");inti;for(i=0;i<array.length;i++){try{array[i]=Integer.parseInt(br.readLine());}catch(Exceptione){System.out.println("An error Occurred");}}System.out.println("The initial array is");System.out.println(Arrays.toString(array));mergeSort(array,0,array.length-1);System.out.println("The sorted array is");System.out.println(Arrays.toString(array));}}
Top comments (0)
Subscribe
We're a place where coders share, stay up-to-date and grow their careers.
Top comments (0)