Monday, 27 October 2014

write a C program for Selection sort

#include <stdio.h> #include <conio.h> #define MAXSIZE 50 int arr[MAXSIZE],n; void selectionsort(int arr[],int n); void main() { int i; printf("Enter the size of array\n"); scanf("%d",&n); printf("\nEnter the values \n"); for(i=0;i<n;i++) scanf("%d",&arr[i]); printf("\nArray before sorting \n"); for(i=0;i<n;i++) printf("\t%d",arr[i]); printf("\n\n"); selectionsort(arr,n); printf("\nArray after sorting \n"); for(i=0;i<n;i++) printf("\t%d",arr[i]); } void selectionsort(int arr[],int n) { int i,j,temp,min; for(i=0;i<n-1;i++) { min=i; for(j=i+1;j<n;j++) { if(arr[min]>arr[j]) { min=j; } temp=arr[i]; arr[i]=arr[min]; arr[min]=temp; } } }

Write a C program for Insertion sort

#include<stdio.h> int main(){ int i,j,s,temp,a[20]; printf("Enter total elements: "); scanf("%d",&s); printf("Enter %d elements: ",s); for(i=0;i<s;i++) scanf("%d",&a[i]); for(i=1;i<s;i++){ temp=a[i]; j=i-1; while((temp<a[j])&&(j>=0)){ a[j+1]=a[j]; j=j-1; } a[j+1]=temp; } printf("After sorting: "); for(i=0;i<s;i++) printf(" %d",a[i]); return 0; }

Bubble sort program using scratch


Friday, 10 October 2014

Linear Search program in C

#include <stdio.h> void main() { int array[10]; int i, num, keynum, found = 0; printf("Enter the value of num \n"); scanf("%d", &num); printf("Enter the elements one by one \n"); for (i = 0; i < num; i++) { scanf("%d", &array[i]); } printf("Input array is \n"); for (i = 0; i < num; i++) { printf("%d\n", array[i]); } printf("Enter the element to be searched \n"); scanf("%d", &keynum); /* Linear search begins */ for (i = 0; i < num ; i++) { if (keynum == array[i] ) { found = 1; break; } } if (found == 1) printf("Element is present in the array\n"); else printf("Element is not present in the array\n"); } Efficiency of Linear Search: To find the number of key comparisons for a successful match, we can add the number required for each comparison and divide by the total number of elements in the list: (1+2+3+4+....+n)/n=n(n+1)/2n

Binary search with out using Recursion

#include <stdio.h> int b_search(int *a,int size,int key) { int first=0,last=size-1,mid; while(first<=last) { mid=(first+last)/2; if(a[mid]==key) return mid; if(a[mid]<key) first=mid+1; else last=mid-1; } return -1; } void main() { int arr[]={11,18,52,95,101,107,135,148,170,185}; printf("%d",b_search(arr,10,185)); }