Kariton Revolution Posted March 31, 2014 Group: Members Topic Count: 161 Topics Per Day: 0.03 Content Count: 429 Reputation: 5 Joined: 11/21/11 Last Seen: January 14, 2017 Share Posted March 31, 2014 #include <stdio.h> int main() { printf("Enter number of elements\n"); for ( c = 0 ; c < n ; c++ ) printf("Enter value to find\n"); int c, first, last, middle, n, search, array[100]; scanf("%d",&n); scanf("%d",&search); first = 0; middle = (first+last)/2; first = middle + 1; { if ( array[middle] < search ) printf("Enter %d integers\n", n); else if ( array[middle] == search ) scanf("%d",&array[c]); { printf("%d found at location %d.\n", search, middle+1); break; } else last = middle - 1; last = n - 1; while( first <= last ) } if ( first > last ) ); return 0; middle = (first + last)/2; } printf("Not found! %d is not present in the list.\n", search i need to become like this the output Quote Link to comment
Tokei Posted April 7, 2014 Group: Members Topic Count: 16 Topics Per Day: 0.00 Content Count: 696 Reputation: 721 Joined: 11/12/12 Last Seen: 2 hours ago Share Posted April 7, 2014 i need to become like this the output 123123.jpg Why is the sample code such a mess! Anyway... you might want to perform a couple of checks on the inputs. #include <iostream> #include <algorithm> using namespace std; // These algorithms are usually shown as recursive, this example does not int _binarySearch(int valueToFind, int * values, int numberOfElements) { int startIndex = 0; int endIndex = numberOfElements - 1; int middleIndex; while (startIndex <= endIndex) { middleIndex = (startIndex + endIndex) / 2; if (valueToFind == values[middleIndex]) { return middleIndex; } else if (valueToFind < values[middleIndex]) { endIndex = middleIndex - 1; } else { startIndex = middleIndex + 1; } } return -1; } int main(void) { int numberOfElements; int valueToFind; cout << "Enter number of elements" << endl; cin >> numberOfElements; cout << "Enter " << numberOfElements << " integers" << endl; int * values = new int[numberOfElements]; for (int i = 0; i < numberOfElements; i++) { cin >> values[i]; } cout << "Enter value to find" << endl; cin >> valueToFind; sort(values, values + numberOfElements); int position = _binarySearch(valueToFind, values, numberOfElements); if (position < 0) { cout << "Not found! " << valueToFind << " is not present in the array list." << endl; } else { // 0-based position, put position + 1 if you want 1-based position cout << valueToFind << " found at location " << position << "." << endl; } delete[] values; values = NULL; system("PAUSE"); return 0; } Quote Link to comment
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.