Given an positive integer x
and a sorted positive integer array A
Is there any algorithm faster than O(N)
to determine if any element in A
is a multiple of x
? There are no negative elements in A
.
Naive looping A
once is my only idea so far, I do not know if there is any way to make use of the fact that A
is sorted to speed it up.
Since all sorting algorithms are bound below by Ω(n), I would argue that both radix sort and bucket sort are the fastest algorithms for sorting an array of integers.
Show activity on this post. Is normally always the fastest and easiest to implement when an array is already nearly or completely sorted. As we have less operations. Selection sort will still do pair wise comparison and binary sort will also be slightly slower.
In computer science, binary search, also known as half-interval search, logarithmic search, or binary chop, is a search algorithm that finds the position of a target value within a sorted array. Binary search compares the target value to the middle element of the array.
Elements in a sorted array can be looked up by their index (random access) at O(1) time, an operation taking O(log n) or O(n) time for more complex data structures.
This seems to depend very much on the size of x
and the number of elements within A
, and particularly the number of candidate multiples of x
within A
.
Binary-searching a specific number within A
takes O(log(n)) time (n being the number of elements within A
), so if there are k
possible multiples of x
between the first and the last element of A
, it will take O(k * log(N))
to check them all. If that number is smaller than n
, you can use this algorithm, otherwise just do a linear search.
(Also, there are probably a few small optimizations to above algorithm. E.g., once you checked x*i
(and did not find it), you can use the position where x*i
should have been as the lower bound when searching for x*(i+1)
instead of the very first element of the array.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With