Advertisement
Guest User

Untitled

a guest
Oct 16th, 2019
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.42 KB | None | 0 0
  1. #include<iostream>
  2. using namespace std;
  3. int linearSearch( const int array[], int key, int size )
  4. {
  5. for ( int i = 0; i < size; i++ ) {
  6. if ( array[i] == key ) {
  7. return i; //return the location in array
  8. }
  9. }
  10. return -1; //key not found
  11. }
  12.  
  13. int binarySearch( const int array[], int key, int low, int high )
  14. {
  15. int middle; //the middle index number of the array
  16. while ( low <= high ) {
  17. middle = ( low + high ) / 2;
  18. if ( key == array[ middle ] ) {
  19. return middle;
  20. }
  21. else if ( key < array[ middle ] ) {
  22. high = middle - 1; //reset high index to left side
  23. }
  24. else {
  25. low = middle + 1; //reset low index to right side
  26. }
  27. }
  28. return -1; //key not found
  29. }
  30. /*-Steps to do:
  31. Declare variables and array with 5 elements to store integer.
  32. Prompt user to key in 5 integer numbers and store in your array.
  33. Asked you user to key in a search key/ target.
  34. Call you linear search to get the position of the target in the array.
  35. Call you binary search to get the position of the target in the array.
  36. Display the position if you found the value or "Key not found" if the key not in the array*/
  37.  
  38. int main (){
  39. int SIZE = 5;
  40. int num[SIZE];
  41. int key;
  42. int check1;
  43. int check2;
  44.  
  45. for (int i = 0;i < SIZE;i++){
  46. cout << "Please enter number " << i + 1 << " :";
  47. cin >> num[i];
  48. }
  49. cout<<"Please enter the key search number :";
  50. cin>>key;
  51.  
  52. check1=linearSearch(num,key,SIZE);
  53. if(check1!=-1){
  54. cout<<"key found " << check1 <<"\n";
  55. }
  56. else{
  57. cout<<"Key not found\n";
  58. }
  59.  
  60. check2=binarySearch(num,key,0,SIZE-1);
  61. if(check2!=-1){
  62. cout<<"key found " << check2 <<"\n";
  63. }
  64. else{
  65. cout<<"Key not found\n";
  66. }
  67.  
  68. return 0;
  69.  
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement