Servo changes its position randomly

Hello everyone,
I'm trying to make a system that separates black balls and white balls. For this, I've used a servo and code is this:
#include <Servo.h>
Servo myservo;
int ldr1 = 5;
int ldr2 = 6;
int val;
int state1;
int state2;

void setup () {
myservo.attach(9);
pinMode(ldr1, INPUT);
pinMode(ldr2, INPUT);
}
void loop() {
state1 = digitalRead(ldr1);
state2 = digitalRead(ldr2);
if(state1 == HIGH && state2 == HIGH) {
val = 1500;
}

else if(state1 != HIGH && state2 == HIGH) {
val = 2000;
}

else if(!state2) {
val = 1000;
}
myservo.writeMicroseconds(val);
delay(200);

}

But I have a problem and is that the servo when "state1" and "state2" are HIGH it works but only during a few seconds, and then change its position to "!state2" where it keeps also during a few moments and later returns to the first position. Can anyone help me, please?
If it's for help, I've used 2 ldr to detect the colours and this servo: "micro servo HD-1160A".

Some serial.Print statements would be useful to see whether power issues are resetting the arduino and to get an idea of what your state variables are getting set to.

Do you use a separate power supply for the servo?

I assume that LDR refers to a light dependent resistor, and I assume you have this wired with a series resistor to act as a voltage divider with the Arduino input connected between the. This will give a voltage that varies with light level. However, it would be pure chance whether the readings corresponding to black and white balls happened to be the right side of the threshold voltage for a digital read. Before you consider trying to use the values to control anything, make sure that your LDR hardware and the software reading from it is consistently giving the correct values. I would have thought you would need to use an analog input and compare the analog reading against a suitable threshold, chosen by trial and error under realistic ambient conditions, but if you're lucky you might find that with the right series resistor you can get it to work with a digital read.

Thanks for the answers, I forgot to mention that I used the LDRs with a transistor and a relay, as an amplifier, like the lines followers, so that's why I used the digital pins. But it doesn't work and I think that probably something in the code is wrong.
If it is for help, the LDRs have an external supply and the Servo is powered by the Arduino.

and the Servo is powered by the Arduino.

Wrong. Servos draw way too much current to be powered by an Arduino.

I forgot to mention that I used the LDRs with a transistor and a relay, as an amplifier, like the lines followers,

Line follower sensors are analog devices. They don't determine that the line is or is not present. They determine how close/far the line is from the center sensor. That is why you need more than one.