Saturday, 4 November 2017

C Program to sort given set of numbers in ascending/descending order using Insertion sort and also search a number using linear search.

#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
void insertion_sort(int a[],int);
void linear_search(int a[],int, int);
void main()
{
int data[100],i,n,element,ch;
while(1)
{
clrscr();
printf("****MENU****\nEnter 1 to apply insertion sort\nEnter 2 to search an element using Linear Search\nEnter 3 for exit\nEnter your choice\n");
scanf("%d",&ch);
switch(ch)
{
case 1:
printf("Enter the number of elements in array \n");
scanf("%d",&n);
printf("Enter array elements\n");
for(i=0;i<n;i++)
{
printf("enter %d element\n",i+1);
scanf("%d",&data[i]);
}
insertion_sort(data,n);
break;
case 2:
printf("Enter the number of elements in array \n");
scanf("%d",&n);
printf("Enter array elements\n");
for(i=0;i<n;i++)
{
printf("enter %d element\n",i+1);
scanf("%d",&data[i]);
}
printf("Enter the element you want to search for\n");
scanf("%d",&element);
linear_search(data,n,element);
break;
case 3:
exit(0);
default:
printf("You have entered wrong choice\n");
}
getch();
}
}
void insertion_sort(int a[],int n)
{
int i,j,temp;
for(i=1;i<n;i++)
{
j=i;
temp=a[j];
while(j>0 && temp<a[j-1])
{
a[j]=a[j-1];
j--;
}
a[j]=temp;
}
printf("After sorting array elements are:- \n");
for(i=0;i<n;i++)
printf("%d\n",a[i]);

}
void linear_search(int a[],int n,int element)
{
int i;
for(i=0;i<n;i++)
{
if(a[i]==element)
{
printf("Element found at location %d\n",i+1);
return;

}


Input/Output:




No comments:

Post a Comment