Friday, December 19, 2014

Binary Search in c lang



Split an Array from Specified Position & Add First Part to the End

#include 
#include    
void main ()
{
int number[30];
int i, n, a, j;
clrscr();   
printf("Enter the value of n\n");
scanf("%d", &n);
printf("enter the numbers\n");
for (i = 0; i < n; ++i)
scanf("%d", &number[i]);
printf("Enter the position of the element to split the array \n");
scanf("%d", &a);
for (i = 0; i < a; ++i)
{
number[n] = number[0];
for (j = 0; j < n; ++j)
{
number[j] = number[j + 1];
}
}
printf("The resultant array is\n");
for (i = 0; i < n; ++i)
{
printf("%d\n", number[i]);
}
       getch();
       }
 
Output

Enter the value of n
4
enter the numbers
3
678
345
876
Enter the position of the element to split the array
3
The resultant array is
876
3
678
345


Accept Sorted Array and do Search using Binary Search

 
 #include 
#include 
void main()
{
    int array[10];
    int i, j, num, temp, keynum;
    int low, mid, high;
    clrscr();
    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 elements \n");
    for (i = 0; i < num; i++)
    {
        printf("%d\n", array[i]);
    }
    
    for (i = 0; i < num; i++)
    {
        for (j = 0; j < (num - i - 1); j++)
        {
            if (array[j] > array[j + 1])
            {
                temp = array[j];
                array[j] = array[j + 1];
                array[j + 1] = temp;
            }
        }
    }
    printf("Sorted 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);
    low = 1;
    high = num;
    do
    {
        mid = (low + high) / 2;
        if (keynum < array[mid])
            high = mid - 1;
        else if (keynum > array[mid])
            low = mid + 1;
    } while (keynum != array[mid] && low <= high);
    if (keynum == array[mid])
    {
        printf("Search successful \n");
    }
    else
    {
        printf("Search failed \n");
    }
getch();
}
 
Output
 
Enter the value of num
5
Enter the elements one by one
23
90
56
15
58
Input array elements
23
90
56
15
58
Sorted array is...
15
23
56
58
90
Enter the element to be searched
58
Search successful
 
Enter the value of num
4
Enter the elements one by one
1
98
65
45
Input array elements
1
98
65
45
Sorted array is...
1
45
65
98
Enter the element to be searched
6
Search failed

No comments:

Post a Comment