Use a Binary Search on an Int Array Sorted in Descending Order

How to binary search in an array which is in an descending order?

Try foll instead.

Assumption: a is your array, i = start, j= end, x is the element you're trying to find. Foll will return -1 if x not in a

static int searchDescendingGT(double[] a, int i, int j, double x) {
while (i <= j) {

int m = (i + j) / 2;

if (a[m] == x) {
return m;
} else if (a[m] < x) {
j = m - 1;
} else {
i = m + 1;
}
}
return -1;

}

Does Arrays.BinarySearch require that the array is sorted in ascending order

Each comparator defines an ordering on the elements of the given type. The requirement is merely that the array elements have to be sorted such that a[0] < ... < a[n-1] for some valid definition of <. That definition does not have to correspond to our conventional notion of < for e.g. numbers -- indeed, it could even be defined as being the conventional >.

Binary searching a decreasing list?

Just use upper_bound with the proper comparison function:

  • Your list is reversed (upper_bound usually expects increasing order) so you need to use > rather than <.
  • You want to include the searched element (while upper_bound usually excludes it) so you need to use >= rather than mere >.

int data[] = {10,5,3,1};
auto item = std::upper_bound(std::begin(data), std::end(data), 6,
[](int a, int b) { return a >= b; });

Now you only have to convert the resulting iterator to an index (after checking it is valid):

if (item != std::end(data)) {
auto index = std::distance(std::begin(data), item);
std::cout << index << std::endl;
}
else
std::cout << "not found" << std::endl;

Binary Search in C++: Ascending + Descending Ordered Arrays

Your code works actually, if the element you are searching for is in the array. However, it does not catch incorrect input.

When calling the function, make sure that:

  • first and last are between 0 and (array length - 1)
  • first < last

eg: if the array has 10 elements, first and last must be between 0 and 9.

Try this:

int main() {
int a[] = {134, 232, 233, 234, 587, 623, 793, 802, 963, 1074};
int b[] = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1};
int na = binarySearch(a, 587, 0, 9);
int nb = binarySearch(b, 3, 0, 9);

printf("na: %d\n", na); // prints 'na: 4'
printf("nb: %d\n", nb); // prints 'nb: 7'
}

If the element you are searching for is not in the array,
then the recursion does never terminate,
you can fix that by adding the following to the head of binarySearch():

if (first == last && k != arr[first])
return -1;

How to sort integer array in ascending and descending order using lambda only in java

You could sort the input of type Integer[] as :

Integer[] arr2 = new Integer[] {54,432,53,21,43};
Arrays.sort(arr2, Comparator.reverseOrder());

or possibly with primitive types as :

int[] arr2 = new int[]{54, 432, 53, 21, 43};
int[] sortedArray = Arrays.stream(arr2)
.boxed()
.sorted(Comparator.reverseOrder()) // just use 'sorted()' for ascending order
.mapToInt(Integer::intValue)
.toArray();

or further using a trick from one of the existing answers (do note that it should be cautiously used with boundary values though) :

int[] sortedArray = Arrays.stream(arr2)
.map(i -> -i).sorted().map(i -> -i) // just use 'sorted()' for ascending order
// Edit - use map(i -> ~i).sorted().map(i -> ~i) to be safe from the issue with Integer.MIN_VALUE
.toArray();

Edit: For an in-place ascending order sort, you just need to perform :

int[] arr2 = new int[]{54, 432, 53, 21, 43};
Arrays.sort(arr2);

Binary Search Ascending Order Array C++

your condition for binary search is inverted.

if array[middle] < value then you want to search for your element in upper half and not the lower half.

Can a @ManyToOne JPA relation be null?

You need to set:

@ManyToOne(optional = true, fetch = FetchType.LAZY)

not optional=false.

The @Column(nullable=true) is to instruct the DDL generation tool to include a NULL SQL column type constraint.

For more on optional vs nullable, check out this StackOverflow answer.

Cannot make @ManyToOne relationship nullable

I found the solution to my problem. The way the primary key is defined in entity Customer is fine, the problem resides in the foreign key declaration. It should be declared like this:

@ManyToOne
@JoinColumn(columnDefinition="integer", name="customer_id")
private Customer customer;

Indeed, if the attribute columnDefinition="integer" is omitted the foreign key will by default be set as the source column: a not-null serial with its own sequence. That is of course not what we want as we just want the to reference the auto-incremented ID, not to create a new one.

Besides, it seems that the attribute name=customer_id is also required as I observed when performing some testing. Otherwise the foreign key column will still be set as the source column. This is a strange behavior in my opinion. Comments or additional information to clarify this are welcome!

Finally, the advantage of this solution is that the ID is generated by the database (not by JPA) and thus we do not have to worry about it when inserting data manually or through scripts which often happens in data migration or maintenance.



Related Topics



Leave a reply



Submit