I am coding an interview question from Yahoo Software Engineer Intern Interview.
Given an unordered list of numbers, find all pairs that add up to x.
I have a working solution in Java:
public static void main (String args[]){
int[] numbers = new int[]{2, 5, 7, 3, 9, 4, 1, 8}; //input array
int x = 6; //target sum
int[] result = new int[numbers.length]; //stores the output pairs
int count = 0;
int[] sorted = numbers;
Arrays.sort(sorted);
int beg = 0;
int end = numbers.length-1;
while (beg < end){
int sum = sorted[beg] + sorted[end];
if (sum > x)
end--;
else if (sum == x){
result[count++] = sorted[beg];
result[count++] = sorted[end];
end--; beg++;
}
else if (sum < x)
beg++;
}
}
Looking for code review optimizations and best practices.