# Should an algorithm handle invalid inputs and can it have hard-coded paths for certain input data? [duplicate]

I have certain preconditions on input data and I need to design an algorithm for that data. Should I also handle invalid preconditions? Also is it normal that my algorithm will work only for a certain number of inputs, for example 4, and for any smaller number of inputs I'll have "if input.size" clause?

To clarify my question. Well, actually it's a task from a book but anyway. So it says i'm given an array sorted, then swapped so that it looks like "4567123" first part "123" is swapped. So, should I bother to design algoritm for non-swaped case? Also my algoritm doesn't work well for input size 1, 2, 3, so I inserted cases for 1 , 2 ,3. Is it ok. So here is the code:

``````//file SwapedArraySearch.java\
public class SwapedArraySearch {
public static int search(int[] arr) {
switch (arr.length){
case 1:
return arr;
case 2:
return arr > arr?arr:arr;
case 3:
return arr > arr  ? (arr > arr?arr: arr):
(arr > arr?arr: arr);
}
int x = arr;
int n = arr.length/2;
int prevn = arr[n] > x ? arr.length -1 : 1;
int t;
while(prevn != n) {
if (x < arr[n]) {
if (arr[n] > arr [n + 1] )
return arr[n+1];
t = n;
n = n + (prevn - n)/2;
prevn = t;
} else {
if (arr[n - 1] > arr[n])
return arr[n];
t = n;
n = prevn + (n - prevn)/2;
prevn = t;
}
}
return arr > arr ? arr[arr.length - 1] : arr;
}

public static void main(String... args) {
int[] arr = new int[args.length];
for (int i = 0; i < args.length; i++)
arr[i] = Integer.valueOf(args[i]);
System.out.println(search(arr));
}
}
``````

Also I'm bother that it looks too complex. Doesn't it or is it fine?

Also, let's say, binary search, it obviously shouldn't check before run that array was sorted before, right?

• This is probably better off on codereview. – jmoreno Jul 28 '13 at 14:29