Friday, April 8, 2011

#C_CODE: Sorting Algorithms

#include <stdio.h>
 
void BubbleSort(int *ptr, int size)
{
 int i, j;
 for(i=0; i < size-1; i++)
 {
  for(j=0; j < size-1-i; j++)
  {
   if(ptr[j] > ptr[j+1])
   {
    ptr[j]   ^= ptr[j+1];
    ptr[j+1] ^= ptr[j];
    ptr[j]   ^= ptr[j+1];
   }
  }
 }

}

void SelectionSort(int *ptr, int size)
{
 int i,j,min;
 for(i=0; i < size-1;i++)
 {
  min = i;
  for(j=i+1;j < size;j++)
  {
   if(ptr[j] < ptr[min])
    min = j;
  }
  ptr[i]   ^= ptr[min];
  ptr[min] ^= ptr[i];
  ptr[i]   ^= ptr[min];
 }
}

void InsertionSort(int *ptr,int size)
{
 int i,j,index;

 for(i=1; i < size;i++)
 {
  index = ptr[i];
  for(j=i; j>0 && ptr[j-1] > index; j--)
   ptr[j] = ptr[j-1];
  ptr[j] = index;
 }
}

int main()
{
 int i;
 int a[] = {5,7,0,8,4,9,6,1,3,2};
 int b[] = {5,7,0,8,4,9,6,1,3,2};
 int c[] = {5,7,0,8,4,9,6,1,3,2};

 BubbleSort(a,10);
 printf("\nBubble sort: ");
 for(i=0;i<10;i++)
  printf("%d ",a[i]);

 SelectionSort(b,10);
 printf("\nSelection sort: ");
 for(i=0;i<10;i++)
  printf("%d ",a[i]);

 InsertionSort(c,10);
 printf("\nInsertion sort: ");
 for(i=0;i<10;i++)
  printf("%d ",a[i]);
 
 fflush(stdin);
 getchar();
}

Ref: blog.Codebeach.com

No comments: