728x90 AdSpace

Latest News

Saturday, September 12, 2015

Sorting


     មេរៀននេះណែនាំអោយយើងស្វែងយល់ពីយុទ្ធសាស្ត្រាមួយចំនួនរបស់ការតម្រៀប ទិន្ន័យ
ដូចជាយុទ្ធសាស្រ្ត Bubble Sort , Selection Sort , Insertion Sort និង Merge Sort ។

​​     1. Bubble Sort 


#include<stdio.h>
#include<conio.h>
void bubblesort(int a[],int n)
{
int temp;
for(int i=0;i<n;i++)
{
 for(int j=0;j<(n-1)-i;j++)
    {
     if(a[j]>a[j+1])
     {
     temp=a[j];
     a[j]=a[j+1];
     a[j+1]=temp;
     }
    }
}
}
void main()
{
 clrscr();
 int a[6]={22,12,34,21,65,2};
 printf("Array not sorting\n");
 for(int i=0;i<6;i++)
 printf("%d\t",a[i]);
 printf("\nArray sorted\n");
 bubblesort(a,6);
 for(i=0;i<6;i++)
  printf("%d\t",a[i]);
 getch();
}

  2. Selection Sort  


 #include<stdio.h>
#include<conio.h>
void sm6(int a[],int n)
{
 int m,t,x;
 for(int i=0;i<n;i++)
    {
      m=a[i];
      t=i;
    for(int j=i+1;j<n;j++)
if(m>a[j])
{
m=a[j];
t=j;
}
      x=a[t];
      a[t]=a[i];
      a[i]=x;
    }
}
void main()
{
 clrscr();
 int a[10]={1,23,56,56,21,12,34,98,75,49};
 sm6(a,10);
 for(int i=0;i<10;i++)
    printf("%d\t",a[i]);
 getch();
}

     3. Merge Sort


#include<stdio.h>
#include<conio.h>
#define MAX 50

void mergeSort(int arr[],int low,int mid,int high);
void partition(int arr[],int low,int high);

void main()
{
clrscr();
int merge[MAX],i,n;

printf("Enter the total number of elements: ");
scanf("%d",&n);

printf("Enter the elements which to be sort: \n");
for(i=0;i<n;i++)
{
scanf("%d",&merge[i]);
}

partition(merge,0,n-1);

printf("After merge sorting elements are: ");
for(i=0;i<n;i++)
{
printf("%d ",merge[i]);
}
getch();
}

void partition(int arr[],int low,int high)
{
int mid;

if(low<high)
{
mid=(low+high)/2;
partition(arr,low,mid);
partition(arr,mid+1,high);

mergeSort(arr,low,mid,high);
}
}

void mergeSort(int arr[],int low,int mid,int high)
{
int i,m,k,l,temp[MAX];

l=low;
i=low;
m=mid+1;

while((l<=mid)&&(m<=high))
{
if(arr[l]<=arr[m])
{
temp[i]=arr[l];
l++;
}
else
{
temp[i]=arr[m];
m++;
}
i++;
}

if(l>mid)
{
for(k=m;k<=high;k++)
{
temp[i]=arr[k];
i++;
}
}
else
{
for(k=l;k<=mid;k++)
{
temp[i]=arr[k];
i++;
}
}

for(k=low;k<=high;k++)
{
arr[k]=temp[k];
}
}
Next
This is the most recent post.
Older Post
  • Blogger Comments
  • Facebook Comments

0 comments:

Post a Comment

Item Reviewed: Sorting Description: Rating: 5 Reviewed By: Raven's Blog
Scroll to Top