Skip to content

Instantly share code, notes, and snippets.

@Aziaev
Last active June 8, 2018 17:15
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 Aziaev/0df3265f9c70624928bc6fe0fbeabe49 to your computer and use it in GitHub Desktop.
Save Aziaev/0df3265f9c70624928bc6fe0fbeabe49 to your computer and use it in GitHub Desktop.
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Integer> arr = new ArrayList();
boolean run = true;
for (int i = 0; i < 10; i++) {
arr.add(i);
}
for (int value = 0; value < 12; value++) {
int start = 0;
int index = arr.size() / 2;
int end = arr.size() - 1;
while (run) {
int item = arr.get(index);
if (value >= arr.get(end)){
index = end + 2;
run = false;
continue;
}
if (item == value) {
run = false;
} else if (item > value) {
end = index;
index = (start + end) / 2;
} else if (item < value) {
start = index;
index = (start + end) / 2;
}
}
System.out.println("value = " + value + " лучше положить по индексу №: " + (index - 1));
run = true;
}
}
}
Результат:
value = 0 лучше положить по индексу №: -1
value = 1 лучше положить по индексу №: 0
value = 2 лучше положить по индексу №: 1
value = 3 лучше положить по индексу №: 2
value = 4 лучше положить по индексу №: 3
value = 5 лучше положить по индексу №: 4
value = 6 лучше положить по индексу №: 5
value = 7 лучше положить по индексу №: 6
value = 8 лучше положить по индексу №: 7
value = 9 лучше положить по индексу №: 10
value = 10 лучше положить по индексу №: 10
value = 11 лучше положить по индексу №: 10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment