#include #include bool binSearch(const int *a, int n, int x, int* index); int main() { FILE* in = fopen("input.txt", "r"); if (in == NULL) { perror("Cannot open input file"); return -1; } int x; int n = 0; while (fscanf(in, "%d", &x) == 1) { ++n; } rewind(in); if (n < 1) { fprintf(stderr, "Empty input file.\n"); return -1; } if (fscanf(in, "%d", &x) != 1) { fprintf(stderr, "Incorrect input file.\n"); return -1; } --n; int *a = new int[n]; int m = 0; for (int i = 0; i < n; ++i) { if (fscanf(in, "%d", &(a[i])) == 1) { ++m; } } fclose(in); int index; bool found = binSearch(a, m, x, &index); if (found) printf("Element is found, index=%d\n", index); else printf("Element is not found, index=%d.\n", index); FILE* out = fopen("output.txt", "w"); if (in == NULL) { perror("Cannot open output file"); return -1; } /* for (int i = 0; i < m; ++i) { if (i > 0) { if (i % 10 == 0) fprintf(out, "\n"); else fprintf(out, " "); } fprintf(out, "%d", a[i]); } fprintf(out, "\n"); */ fprintf(out, "%d\n", index); fclose(out); return 0; } bool binSearch( // Binary search in ordered array const int *a, // Pointer to the beginning of array int n, // Number of elements in array int x, // Element to find int *idx // Result: *idx is such index that // a[*idx - 1] < x <= a[*idx] ) { // Return value: true when x is found // Consider first the special cases if (n < 0) { // Array is empty *idx = 0; return false; } else if (x <= a[0]) { // x <= minimal element of array *idx = 0; return (x == a[0]); } else if (x > a[n-1]) { // x > maximal element of array *idx = n; return false; } else { // General case assert( n > 0 && a[0] < x && x <= a[n-1] ); int i0 = 0; // [i0, i1] is the current segment of array int i1 = n-1; // that may contain x while (i1 - i0 > 1) { // loop while the length of segment > 1 assert(a[i0] < x && x <= a[i1]); // Invariant int c = (i0+i1)/2; // Middle of the segment if (a[c] < x) { // if x > middle element i0 = c; // then select the right part } else { // else i1 = c; // select the left part } // end if } // end loop assert(a[i1-1] < x && x <= a[i1]); *idx = i1; // Write the resulting index return (x == a[i1]); // Return true if x is found } }