Friday, October 25, 2013

MERGE SORT ALGORITHM

/*

TOPIC: MERGE SORT ALGORITHM.
DATE:4/10/2012
*/
import java.io.*;
class Sequence
{
BufferedReader br;
int a[];
int size,temp;
boolean flag;
int l1,l2,l3,k,a1,a2,i,j;
Sequence()
{
br = new BufferedReader ( new InputStreamReader(System.in));
flag=true;
}
void create()throws IOException
{
System.out.println("enter size of array: ");
size=Integer.parseInt(br.readLine());
a=new int[size];
insert();
}
void insert()throws IOException
{
System.out.println("INSERT THE ELEMENTS INTO THE ARRAY");
for(i=0;i<size;i++)
a[i]=Integer.parseInt(br.readLine());
}
void MergeSort()

{
MergeSort(0,a.length-1);
}
void MergeSort(int lo,int n)

{
int low=lo;
int high=n;
if(low>=high)
return;
int middle=(low+high)/2;
MergeSort(low,middle);
MergeSort(middle+1,high);
int end_low=middle;
int start_high=middle+1;
while((low<=end_low)&&(start_high<=high))
{
if(a[low]<a[start_high])
{
low++;
}
else{
int temp=a[start_high];
for(int k=start_high-1;k>=low;k--)
a[k+1]=a[k];
a[low]=temp;
low++;
end_low++;
start_high++;
}
}
}

void display()
{
for(i=0;i<a.length;i++)
System.out.print(a[i]+" ");
System.out.println();
}
}
class MergeSort
{
public static void main(String args[])throws Exception
{
Sequence s=new Sequence();
s.create();
System.out.println("BEFORE SORTING");
s.display();
s.MergeSort();
System.out.println("AFTER SORTING");
s.display();
//System.out.println("THANK U CODED BY TG");
}
}
/*
OUTPUT:
enter size of array:
8
INSERT THE ELEMENTS INTO THE ARRAY
55
4
98
7
65
26
3
444
BEFORE SORTING
55              4               98              7               65             26               3               444
AFTER SORTING
3               4               7               26              55             65               98              444

*/

No comments:

Post a Comment