prowessapps.in Searching and Sorting Programs

 C Program to search an element in Array using "Linear Search".

#include<stdio.h>
int main() {
 int a[10]={10,14,19,26,27,31,33,35,42,44};
 int i,n,flag=0;

 printf("Enter no. to Search: ");
 scanf("%d",&n);
 for(i=0; i<=10; i++) {
  if(a[i]==n) {
   flag=1;
   break;
  }
 }
 if(flag==1) {
  printf("%d found at %d pos",n,i);
 }
 else {
  printf("Number not found.");
 }
 return 0;
}
OUTPUT :
OUTPUT : 1
Enter no. to Search: 33
33 found at 6 pos

OUTPUT : 2
Enter no. to Search: 71
Number not found.

 C Program to search an element in Array using "Binary Search".

#include<stdio.h>
int main() {
 int beg, end, mid, n;
 int ar[9]={1,2,3,4,5,6,7,8,9};
 printf("Enter no. to Search:");
 scanf("%d", &n);
 beg = 0;
 end = 8;
 while (beg < = end) {
  mid = (beg+end)/2;	
  if(ar[mid] == n) {
   printf("Found at %d pos\n",mid);
   break;
  }
  else if(ar[mid] < n) {
   beg = mid + 1;
  }
  else {
   end = mid - 1;
  }
 }
 if (beg > end)
  printf("Not found!");
 return 0;   
}
OUTPUT :
OUTPUT : 1
Enter no. to Search: 8
Found at 7 pos.

OUTPUT : 2
Enter no. to Search: 17
Not found.

 Arrange the array elements in ACS order using Bubble Sort.

#include<stdio.h>
int main(){
 int i,j,temp;
 int ar[8] = {6,5,3,1,8,7,2,4};
 printf("BEFORE SORTING :\n");
 for(i=0; i < 8; i++) {
   printf("%d  ",ar[i]);
 }
 for(i=1; i<=8; i++) {
  for(j=0; j < 8-i; j++) {
   if(ar[j]>ar[j+1]) {
         temp=ar[j];
	 ar[j]=ar[j+1];
	 ar[j+1]=temp;
     }
   }
 }
 printf("\n\nAFTER SORTING :\n");
 for(i=0; i < 8; i++) {
  printf("%d  ",ar[i]);
 } 
 return 0;	
}
OUTPUT :
BEFORE SORT :
6 5 3 1 8 7 2 4

AFTER SORT : 
1 2 3 4 5 6 7 8

 Arrange the array elements in ACS order using "Selection Sort".

#include<stdio.h>
int main(){
 int i,j,temp;
 int ar[5] = {25,17,31,13,2};
 printf("BEFORE SORTING :\n");
 for(i=0; i < 5; i++) {
   printf("%d  ",ar[i]);
 }
 for(i=0; i < 5-1;i++){
     for(j=i+1; j < 5; j++){
	  if(ar[i]>ar[j]){
	      temp=ar[i];
 	      ar[i]=ar[j];
              ar[j]=temp;
	}
   }
 }

 printf("\n\nAFTER SORTING :\n");
 for(i=0; i < 5; i++) {
  printf("%d  ",ar[i]);
 } 
 return 0;	
}
OUTPUT :
BEFORE SORT :
25 17 31 13 2

AFTER SORT : 
2 13 17 25 31



Get it on Google Play


CONTACT DETAILS

info@prowessapps.in
(8AM to 10PM):

+91-9026070669 , +91-9451396824

© 2016, prowessapps.in, All rights reserved