Probably the most important thing is that your algorithm is not recursive. A recursive function is a function that calls itself.
In view of that finding out what is wrong with it is pretty much irrelevant. However, the best way for you to find out where it goes wrong is to step through your program and see how the variables evolve.
I'll note a few things:
- Use meaningful variable names instead of a1, k, n1. It's much easier to follow a program when the variable names are words that explain what's in them (e.g. your inputArray).
- There's no point in
x = somevalue;
val = x;
%... code that never use x
simply use
val = somevalue; %and use a better name than val
- it's unlikely that your
if inputArray<n1
does what you want. The if will only be true if all elements of inputArray are smaller than n1. If that is indeed what you intended to do, then use
if all(inputArray < n1)
to remove the ambiguity.
edit: What sort of algorithm are you trying to implement?. Some small parts of your code look like a quickselect but the majority does not. In particular, for a quickselect, at some point, you need to do something with your mid variable that is currently completely unused.