Open muhtalhakhan opened 1 year ago
hey @muhtalhakhan i want to contribute to this issue. here's code in java //Merge sort-O(nlogn) import java.util.*; class Mergesort { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("enter n"); int n = sc.nextInt(); int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = sc.nextInt(); } System.out.println("Merge sort:"); div(a, 0, n-1); p(a); } // print array static void p(int a[]) { for (int i : a) { System.out.print(i + " "); } } static void div(int a[],int l,int r) { if(l>=r) { return ; } int m=l+(r-l)/2; div(a,l,m); div(a,m+1,r); merge(a,l,m,r);
}
static void merge(int a[],int l ,int m,int r)
{
List<Integer>ls=new ArrayList<>();
//here low,high are current pointers
int low=l;
int high=m+1;
while(low<=m && high<=r)
{
if(a[low]<=a[high])
{
ls.add(a[low]);
low++;
}
else
{
ls.add(a[high]);
high++;
}
}
while(low<=m)
{
ls.add(a[low]);
low++;
}
while(high<=r)
{
ls.add(a[high]);
high++;
}
for(int i=l;i<=r;i++)
{
a[i]=ls.get(i-l);
}
}
}
we can also add the variation of the merge sort algorithm which uses recursion.