C++ About Merge Sort

Merge sort is a sorting algorithm in computer science designed to meet the needs of sorting on a data set that does not allow to be stored in computer memory because the amount is too large. This algorithm was invented by John von Neumann in 1945.

Sintak Program :

#include <iostream.h>
#include <conio.h>
#include <stdio.h>
int a[50];
void merge(int,int,int);

void merge_sort(int low,int high) //fungsi marge_sort
{
int mid;
if(low<high)
{
mid=(low+high)/2;
merge_sort(low,mid);
merge_sort(mid+1,high);
merge(low,mid,high);
}
}

void merge(int low,int mid,int high) //fungsi marge
{
int h,i,j,b[50],k;
h=low;
i=low;
j=mid+1;

while((h<=mid)&&(j<=high))
{
if(a[h]<=a[j])
{
b[i]=a[h];
h++;
}
else
{
b[i]=a[j];
j++;
}
i++;

}
if(h>mid)
{
for(k=j;k<=high;k++)
{
b[i]=a[k];
i++;
}
}
else
{
for(k=h;k<=mid;k++)
{
b[i]=a[k];
i++;
}
}
for(k=low;k<=high;k++) a[k]=b[k];
}

int main() //program utama
{
int num,i;

cout<<“********************************************************************************”<<endl;
cout<<” MERGE SORT PROGRAM”<<endl;

cout<<“********************************************************************************”<<endl;
cout<<endl<<endl;
cout<<“Please Enter THE NUMBER OF ELEMENTS you want to sort [THEN PRESS ENTER]: “;
cin>>num; //masukan banyak digit yang akan di sort
cout<<endl;
cout<<“Now, Please Enter the ( “<< num <<” ) numbers (ELEMENTS) [THEN PRESS ENTER]:”<<endl;
for(i=1;i<=num;i++) //array 1-num
{
cin>>a[i] ; //masukan digit pertama sampai (num)
}
merge_sort(1,num); //memanggil fungsi marge_sort
cout<<endl;
cout<<“So, the sorted list (using MERGE SORT) will be :”<<endl;
cout<<endl<<endl;

for(i=1;i<=num;i++) //array pengurutan
cout<<a[i]<<” “;

cout<<endl<<endl<<endl<<endl;
getch();
}

explanation:
The program above is a merge sort program is one method ofsorting. Merge sort is done recursively. Step of the algorithm is a data line is divided into 2 subbarisan then sortrecursively and join the results of step 2 of 2 subbarisan aresorted into the sorted sequence.

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Difa Computer

A great WordPress.com site

%d bloggers like this: