Guest User

Untitled

a guest
May 22nd, 2018
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.36 KB | None | 0 0
  1. #include <iostream>
  2. #include <fstream>
  3. void insertionsort (int list[], int n);
  4. int binary_search(int list[], int target, int n);
  5. using namespace std;
  6. int main(void)
  7. {
  8. int list[100],
  9. i=0,
  10. n=0;
  11.  
  12. cout << "此程式陣列大小為100,請勿輸入超過100個數\n";
  13. while(list[i-1] != -1)
  14. {
  15. cout << "請輸入陣列(欲要結束請輸入-1):";
  16. cin >>list[i];
  17. i++;
  18. n++;
  19. }
  20. n = n-1;
  21. insertionsort(list,n);
  22. for(i=0; i<n; i++)
  23. cout << list[i] << " ";
  24. cout << "\n";
  25. system("pause");
  26. return 0;
  27. }
  28.  
  29. //Insertionsort use binarysearch
  30. void insertionsort (int list[], int n)
  31. {
  32. int i,j,x,y;
  33. for(i=1; i<n; i++)
  34. {
  35. x = list[i];
  36. j = i-1;
  37. y=binary_search(list, x, i);
  38.  
  39. while(j>=y && x<list[j])
  40. {
  41. list[j+1] = list[j];
  42. j--;
  43. }
  44. list[j+1] = x;
  45. }
  46.  
  47. }
  48.  
  49. //二分法
  50. int binary_search(int list[], int target, int n)
  51. {
  52. int bottom=0,
  53. middle,
  54. top,
  55. found=0;
  56. top = n-1;
  57.  
  58. while(!found && bottom <= top)
  59. {
  60. middle = (bottom + top)/2;
  61. if(list[middle] == target)
  62. found = 1;
  63. else if(list[middle] > target)
  64. top = middle-1;
  65. else
  66. bottom = middle+1;
  67. }
  68. return(middle);
  69. }
Add Comment
Please, Sign In to add comment