0
Problem with Binary in java
Hello there! So i have a project in data structure and algorithms and i have to sort an array using binary search but i cant make it right. Can someone help me?
8 odpowiedzi
+ 3
Where is your source code. Attached the attempt with your question and point out the problem you have in.
Easy for us to resolve!
+ 3
Elen If you're looking for a way to dynamically sort an array of numbers after insertions. First start with an empty array or an array that is already sorted. For each new number you want to insert, add the number at the end of the array. Compare the new number with the element just before it. If the new number is smaller, swap it with the previous element.
Repeat comparing the new number with the element just before it and again swap it with the previous element until the new number is in its correct sorted position. After all insertions are done, you will have a fully sorted array. Try this code snippet I give you. If you find any issues, let me inform here. It will be resolved according the type of issues you'll face. Thanks 😊
+ 2
There are a couple of issues in your insert method that need to be fixed. First of all, initialize idx inside the else block where you actually update it. Move the tail++ operation to the end of the else block to avoid incrementing it unnecessarily. Then add a check for inserting an element when the array is empty. Finally make sure to handle the case when the key to be inserted is greater than all existing keys.
Try this resolved code, may be this should be helpful to address some of the issues in the code you provided & improve the functionality of the binary search insertion logic. Enjoy!
https://sololearn.com/compiler-playground/cu80wHOGra1A/?ref=app
+ 1
Is that helping? нттp⁴⁰⁶
+ 1
The problem is that it doesn't sort right the numbers and after some insertions it puts them at the wrong position. I am just confused how to sort the array and see where the num i want to insert is going to go and i cant find it. I will try your suggestions and come up later. Thansks!
+ 1
`нттp⁴⁰⁶ Hello again! You saved my life the code worked perfectly finally and i can't thank you enough!!!
+ 1
You're welcome 🤗