Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include "StdAfx.h"
- #include <stdio.h>
- #include <malloc.h>
- #include <stdlib.h>
- int binarysearch(int a, int mass[], int n)
- {
- int low, high, middle;
- low = 0;
- high = n - 1;
- while (low <= high)
- {
- middle = (low + high) / 2;
- if (a < mass[middle])
- high = middle - 1;
- else if (a > mass[middle])
- low = middle + 1;
- else
- return middle;
- }
- return -1;
- }
- int main(){
- int *mass, *mass2;
- int i, n, newElement, location, search, k;
- printf("Enter the size : ");
- scanf_s("%d", &n);
- mass = (int*)malloc(n * sizeof(int));
- for (i = 0; i < n; i++)
- {
- printf("a[%d] = ", i);
- scanf_s("%d", &mass[i]);
- }
- for (i = 1; i < n; i++)
- {
- newElement = mass[i];
- location = i - 1;
- while (location >= 0 && mass[location] > newElement)
- {
- mass[location + 1] = mass[location];
- location = location - 1;
- }
- mass[location + 1] = newElement;
- }
- printf("\nResult sort\n");
- for (i = 0; i < n; i++)
- {
- printf("mass[%d] = %d ", i, mass[i]);
- }
- printf("\nEnter search\n");
- scanf_s("%d", &search);
- k = binarysearch(search, mass, n);
- if (k != -1)
- {
- printf("The index of the element is %d\n", k);
- }
- else
- printf("The element isn't found!\n");
- free(mass);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement