Advertisement
boyan16-z

sorting by insertion and binary search

Mar 21st, 2018
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.21 KB | None | 0 0
  1. #include "StdAfx.h"
  2. #include <stdio.h>
  3. #include <malloc.h>
  4. #include <stdlib.h>
  5.  
  6. int binarysearch(int a, int mass[], int n)
  7. {
  8. int low, high, middle;
  9. low = 0;
  10. high = n - 1;
  11. while (low <= high)
  12. {
  13. middle = (low + high) / 2;
  14. if (a < mass[middle])
  15. high = middle - 1;
  16. else if (a > mass[middle])
  17. low = middle + 1;
  18. else
  19. return middle;
  20. }
  21. return -1;
  22. }
  23.  
  24. int main(){
  25. int *mass, *mass2;
  26. int i, n, newElement, location, search, k;
  27.  
  28. printf("Enter the size : ");
  29. scanf_s("%d", &n);
  30. mass = (int*)malloc(n * sizeof(int));
  31.  
  32. for (i = 0; i < n; i++)
  33. {
  34. printf("a[%d] = ", i);
  35. scanf_s("%d", &mass[i]);
  36. }
  37.  
  38. for (i = 1; i < n; i++)
  39. {
  40. newElement = mass[i];
  41. location = i - 1;
  42. while (location >= 0 && mass[location] > newElement)
  43. {
  44. mass[location + 1] = mass[location];
  45. location = location - 1;
  46. }
  47. mass[location + 1] = newElement;
  48. }
  49.  
  50. printf("\nResult sort\n");
  51. for (i = 0; i < n; i++)
  52. {
  53. printf("mass[%d] = %d ", i, mass[i]);
  54. }
  55.  
  56. printf("\nEnter search\n");
  57. scanf_s("%d", &search);
  58.  
  59. k = binarysearch(search, mass, n);
  60. if (k != -1)
  61. {
  62. printf("The index of the element is %d\n", k);
  63. }
  64. else
  65. printf("The element isn't found!\n");
  66. free(mass);
  67. return 0;
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement