Skip to content

Instantly share code, notes, and snippets.

@gansai
Last active October 11, 2015 08:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gansai/b2a49bd0034c471276dd to your computer and use it in GitHub Desktop.
Save gansai/b2a49bd0034c471276dd to your computer and use it in GitHub Desktop.
Given an array and a sum x, find a pair in array which sums up to x. (Brute-force)
/**
* Created by gansai on 11/10/15.
*/
public class FindPairSum_Brute {
public static void main(String args[])
{
int array[] = new int[] { 1, 43, 2, 55, 21, 87, 9 };
int sum = 76;
boolean foundPair = false;
for(int i = 0; i< array.length; i++)
{
for(int j = i+1; j < array.length; j++)
{
if(array[i] + array[j] == sum)
{
foundPair = true;
System.out.println("Found the pair which sums up to "+ sum);
System.out.println("They are "+ array[i] + " and " + array[j]);
break;
}
else
continue;
}
if(foundPair)
{
break;
}
else
{
continue;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment