fork download
  1. class Test {
  2.  
  3. public static void main(String[] args) {
  4. int[] sortedArray = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
  5. PrintIntSumValues(6, sortedArray);
  6.  
  7. sortedArray = new int[] {1, 2,3, 12, 23423};
  8. PrintIntSumValues(15, sortedArray);
  9.  
  10.  
  11. sortedArray = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
  12. PrintIntSumValues(100, sortedArray);
  13.  
  14. sortedArray = new int[] {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50};
  15. PrintIntSumValues(48, sortedArray);
  16. }
  17.  
  18. // Print at the system out the first two ints found in the sorted array: sortedInts[] whose sum is equal to Sum in a single pass over the array sortedInts[] with no 0 value allowed.
  19. // i.e. sortedInts[i] + sortedInts[?] = Sum where ? is the target index to be found to complete the task.
  20. static void PrintIntSumValues(int Sum, int sortedInts[]) {
  21. // need to test to see if the Sum value is contained in the array sortedInts. And, if not do nothing.
  22. int offset = sortedInts.length-1;
  23.  
  24. for(int i=0; i<sortedInts.length; i++) {
  25. // ... do some work: algebra and logic ...
  26. if ((sortedInts[i] + sortedInts[offset]) == Sum){
  27. System.out.println("sortedInts[" + i + "]+sortedInts[" + offset + "] sums to " + Sum + ".");
  28. return;
  29. } else {
  30. int remaining = Sum - sortedInts[i];
  31. if (remaining < sortedInts[i] ){
  32. // We need something before i
  33. if (remaining < sortedInts[offset]) {
  34. // Even before offset
  35. offset = 0 + (offset - 0)/2;
  36. } else {
  37. // Between offset and i
  38. offset = offset + (i - offset)/2;
  39. }
  40. } else {
  41. // We need something after i
  42. if (remaining < sortedInts[offset]) {
  43. // But before offset
  44. offset = i + (offset - i)/2;
  45. } else {
  46. // Even after offset
  47. offset = offset + (sortedInts.length - offset)/2;
  48. }
  49. }
  50. }
  51. }
  52. System.out.println("There was no sum :(");
  53.  
  54. }
  55. }
Success #stdin #stdout 0.03s 245632KB
stdin
Standard input is empty
stdout
sortedInts[2]+sortedInts[2] sums to 6.
sortedInts[2]+sortedInts[3] sums to 15.
There was no sum :(
sortedInts[3]+sortedInts[43] sums to 48.