Advertisement
Guest User

Untitled

a guest
Mar 20th, 2019
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.13 KB | None | 0 0
  1. import java.util.Random;
  2.  
  3. public class Homework
  4. {
  5.  
  6. static final int SORTED_ARRAY_SIZE = 20000;
  7. static final int[] sorted_array = new int[SORTED_ARRAY_SIZE];
  8. /*
  9. * Return the index of the target or -1 if not found.
  10. */
  11. public static int binarySearch(int [] element, int target){
  12. int start = 0;
  13. int end = sorted_array.length -1;
  14. int halfway = (end - start) / 2;
  15.  
  16. for (int x = 0; x < sorted_array.length; x++){
  17. if(sorted_array[x] == target){
  18. return x;
  19. }
  20. else if(sorted_array[halfway] > target){
  21. end = halfway -1;
  22. }
  23. else {
  24. start = halfway + 1;
  25. }
  26.  
  27. }
  28. return -1;
  29. }
  30.  
  31. /*
  32. * Return the index of the target or -1 if not found.
  33. */
  34. public static int sequentialSort(int[] element, int target) {
  35. for (int x = 0; x < sorted_array.length; x++)
  36. {
  37. if (sorted_array[x] == target)
  38. {
  39. return x;
  40. }
  41. }
  42. return -1;
  43.  
  44. }
  45.  
  46.  
  47. public static void main(String[] args)
  48. {
  49.  
  50. int[] sorted_array = new int[SORTED_ARRAY_SIZE];
  51.  
  52. for(int i = 0; i < SORTED_ARRAY_SIZE; i++)
  53. {
  54. sorted_array[i] = i*2;
  55. }
  56.  
  57. Random rand = new Random();
  58. int[] random_array = new int[SORTED_ARRAY_SIZE];
  59.  
  60. for(int i = 0; i < SORTED_ARRAY_SIZE; i++)
  61. {
  62. random_array[i] = rand.nextInt(200000);
  63.  
  64. }
  65.  
  66. System.out.println(binarySearch(sorted_array,458));
  67. System.out.println(binarySearch(sorted_array, 19887));
  68. System.out.println(binarySearch(sorted_array, -90));
  69.  
  70. System.out.println(sequentialSort(random_array, 9983));
  71. System.out.println(sequentialSort(random_array, 199327));
  72. System.out.println(sequentialSort(random_array, 22873));
  73. System.out.println(sequentialSort(random_array, 723625));
  74.  
  75.  
  76.  
  77.  
  78. }
  79.  
  80. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement