Problem with Binary in java | Sololearn: Learn to code for FREE!
Novo curso! Todo programador deveria aprender IA generativa!
Experimente uma aula gr√°tis
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?

13th Apr 2024, 6:40 AM
Elen
Elen - avatar
8 Respostas
+ 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!
13th Apr 2024, 6:42 AM
`–Ĺ—ā—āŠč®‚Āī‚Āį‚Ā∂
`–Ĺ—ā—āŠč®‚Āī‚Āį‚Ā∂ - avatar
+ 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 ūüėä
13th Apr 2024, 7:54 AM
`–Ĺ—ā—āŠč®‚Āī‚Āį‚Ā∂
`–Ĺ—ā—āŠč®‚Āī‚Āį‚Ā∂ - avatar
+ 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
13th Apr 2024, 7:28 AM
`–Ĺ—ā—āŠč®‚Āī‚Āį‚Ā∂
`–Ĺ—ā—āŠč®‚Āī‚Āį‚Ā∂ - avatar
13th Apr 2024, 6:50 AM
Elen
Elen - avatar
+ 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!
13th Apr 2024, 7:37 AM
Elen
Elen - avatar
+ 1
`–Ĺ—ā—āp‚Āī‚Āį‚Ā∂ Hello again! You saved my life the code worked perfectly finally and i can't thank you enough!!!
15th Apr 2024, 9:19 PM
Elen
Elen - avatar
+ 1
You're welcome ūü§ó
15th Apr 2024, 9:38 PM
`–Ĺ—ā—āŠč®‚Āī‚Āį‚Ā∂
`–Ĺ—ā—āŠč®‚Āī‚Āį‚Ā∂ - avatar