Menu BAR

FEEL FREE TO ASK ANY PROGRAM and please mention any error if you find it
Showing posts with label Sorting. Show all posts
Showing posts with label Sorting. Show all posts

19 Jan 2013

INSERTION SORTING using C language

Q.) Write a program to implies the insertion sorting method.

Sol)

#include<stdio.h>
#include<conio.h>
int main( )
{
  int arr[30];
  int i,j, size, tmp ;
  printf("---Insertion Sorting Method---\n\n") ;
  printf("Enter the total no. of elements:  ") ;
  scanf("%d", &size) ;
  for(i=0; i<size; i++)
    {
        printf("Enter %d element: ", i+1)  ;
        scanf("%d", &arr[i]) ;
    }

for(i=0; i<size; i++)
   {
       for(j=i-1; j>=0; j--)
         {  
             if(arr[j]>arr[j+1])
                { 
                  tmp=arr[j] ;
                  arr[j]=arr[j+1] ;
                  arr[j+1]=tmp;
                }
             else
                 break;
         }
    }
printf("\n\t --- Insertion Sorted Elements----\n\n") ;

for(i=0; i<size; i++)
    printf("%d", arr[i]) ;
return 0;

}

QUICK SORT using C program

Q.) Write a program to sort the given number of elements using QUICK SORT 


Sol)
#include<stdio.h>
#include<conio.h>

void qsort(int, int, int) ;     //Prototype

int main( )
{
    int arr[30];
    int i, size ;
    printf("Enter total number of Elements:  ") ;
    scanf("%d", &size);
    printf("Enter the Elements: \n")
    for(i=0; i<size; i++)
       scanf("%d", &arr[i]) ;
    qsort(arr, 0, size-1) ;    //calling
    printf("Quick Sorted elements are as:  \n") ;
    for(i=0; i<size; i++)
       printf("%d\t",arr[i]);

    return 0;
}

void qsort(int arr[20], int frst, int last)     //definition
 {
   int i, j, pivot, tmp;
     if(frst<last)
        {
            pivot=frst ;
            i=frst ;
            j=last;
           while(i<j)
             {
                while(arr[i]<=arr[pivot] && i<last)
                      i++  ;

                while(arr[j]>arr[pivot])
                      j-- ;
                if(i<j)
                   {
                         tmp=arr[i];
                         arr[i]=arr[j] ;
                         arr[j]=tmp;
                    }
             }                     //end of while loop
        tmp=arr[pivot] ;
        arr[pivot]= arr[j];
        arr[j]=tmp ;
        qsort(arr,frst,j=1) ;
        qsort(arr, j+1, last) ;
     }                    //end of if statement

}