Advertisement
adesuryadi_

AP//Binarysearch.cpp

May 28th, 2017
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.13 KB | None | 0 0
  1. //Binarysearch.cpp
  2.  
  3. #include <constrea.h>
  4. #include <stdio.h>
  5.  
  6. int main()
  7. {
  8. int n, angka[12],kiri, kanan,tengah,temp,key;
  9. bool ketemu= false;
  10.  
  11. cout<<"\nMasukan jumlah data: ";
  12. cin>>n;
  13.  
  14. for(int i=0;i<n;i++)
  15. {
  16. cout<<"Angka ke- ["<<i<<"]:";
  17. cin>>angka[i];
  18. }
  19.  
  20. for(int i=0; i<n; i++)
  21. {
  22. for(int j=0;j<n-i-1;j++)
  23. {
  24. if(angka [j]>angka[j+1])
  25. {
  26. temp=angka[j];
  27. angka[j]=angka[j+1];
  28. angka[j+1]=temp;
  29. }
  30. }
  31. }
  32.  
  33. cout<<"\nData yang telah diurutkan adalah: ";
  34. for(int i=0; i<n;i++)
  35. {
  36. cout<<angka[i]<<" ";
  37. }
  38.  
  39. cout<<"\nMasukan angka yang dicari: ";
  40. cin>>key;
  41.  
  42. kiri=0;
  43. kanan=n-1;
  44.  
  45. while(kiri<=kanan)
  46. {
  47. tengah=(kiri+kanan)/2;
  48.  
  49. if(key == angka[tengah])
  50. {
  51. ketemu=true;
  52. break;
  53. }
  54. else if (key<angka[tengah])
  55. {
  56. kanan=tengah-1;
  57. }
  58. else
  59. {
  60. kiri=tengah+1;
  61. }
  62. }
  63. if(ketemu==true)
  64. cout<<"Angka ditemukan !";
  65. else
  66. cout<<"Angka tidak ditemukan:";
  67. getch();
  68. //return0;
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement