How can I add an integer to a sorted array using binary search in Java?

  • Context: Java 
  • Thread starter Thread starter pumas
  • Start date Start date
  • Tags Tags
    Array Java Sorting
Click For Summary

Discussion Overview

The discussion revolves around the problem of adding an integer to a sorted array using binary search in Java. Participants explore various methods and considerations for maintaining the sorted order of the array while inserting a new element.

Discussion Character

  • Technical explanation
  • Debate/contested
  • Homework-related

Main Points Raised

  • One participant shares a binary search implementation and expresses confusion about how to insert a number while preserving the sorted order.
  • Another participant suggests searching for the next largest number and shifting elements to make space for the new integer, but acknowledges the limitations of static arrays.
  • There is a suggestion that if the array is dynamic, a new array would need to be created to accommodate the additional element.
  • Some participants clarify that the approach to adding an item should involve shifting elements to the right, rather than deleting an item.
  • One participant proposes using a Vector instead of a static array, noting that it automatically grows when necessary.
  • Another participant mentions that using a recursive function for binary search might earn extra points in a school assignment.
  • There is a discussion about the validity of using Vector with primitive types, with some participants correcting others on the proper use of generics in Java.
  • One participant recommends using ArrayList over Vector, citing its advantages.

Areas of Agreement / Disagreement

Participants express differing views on the best approach to insert an integer into a sorted array, with no consensus on a single method. There is also disagreement regarding the use of Vector versus ArrayList and the handling of primitive types in generics.

Contextual Notes

Some participants note the limitations of static arrays and the need for dynamic data structures, while others emphasize the importance of maintaining sorted order during insertion. The discussion includes unresolved technical details regarding implementation.

Who May Find This Useful

This discussion may be useful for individuals learning about data structures in Java, particularly those interested in binary search and array manipulation techniques.

pumas
Messages
15
Reaction score
0
Hello,

I need to write a method that adds an interger to a sorted array of integers. I'm using the following code to search for an interger in the array

private static int binarySearch(int[] list, int key,
int low, int high) {
while (low <= high) {
int mid = (low + high) / 2;
int midVal = list[mid];

if (midVal < key) {
low = mid + 1;
} else if (midVal > key) {
high = mid - 1;
} else {
return mid; // key found
}
}
return -(low + 1); // key not found.
}

I have not done programming in a long time, so I'm very confused on how to write the code to insert a number and preserved the sorted order.
I would appreciate any help

Thanks :smile:
 
Technology news on Phys.org
You could search for the next largest number, store it in a temporary variable and:

1. Replace the number you just stored in the temp variable with the one you want to insert.
2. Use the temporary variable to shift the array down by one.

Eg:
for(i=maxval;i>x;i--) /*x is the position of the next largest number maxval is the largest index number of the array*/

{
arr[x-1]=arr[x];
}
arr=j; //j is the number you want to insert and i=x now

This is good enough for a static array, but for a dynamic one i guess you'd need to create a new array with one more element. I can't help you in the actual coding cause I only know c++. The logic, however, should be the same.
 
He wants to add an item to a list, not delete it, so shouldn't that be:

arr[x+1]=arr[x];

?
 
Last edited:
Thanks for your help
 
Jeff Reid said:
He wants to add an item to a list, not delete it, so shouldn't that be:

arr[x+1]=arr[x];

?

Since the array is static, one item will be deleted. If the array is dynamic, and you want to add an item in the middle, then you use the linked list approach, which is totally different.
 
If you're not required to use an array as your data structure then you should use a Vector instead, which is basically an array that automatically grows when necessary.

Also, if this is a school assignment then you might get extra points if you code your binary search as a recursive function.
 
Last edited:
-Job- said:
If you're not required to use an array as your data structure then you should use a Vector instead, which is basically an array that automatically grows when necessary.

Also, if this is a school assignment then you might get extra points if you code your binary search as a recursive function.

How would you do that (the vector part)?
 
-Job- said:
Use the Vector class:
http://java.sun.com/j2se/1.5.0/docs/api/java/util/Vector.html
Code:
Vector<int> MyVector = new Vector<int>(initialSize)
//add to vector:
MyVector.add(200);
//or insert at location:
MyVector.insertElementAt(232, 0);

The Vector automatically grows.

Vector<int> MyVector is not a valid code

Vector<Integer> is valid, since you cannot pass primitives into the <> tags.

It is generally recommended to use ArrayList instead of Vector class.

That is one can do

ArrayList<Integer> integerList = new ArrayList<Integer>();
integerList.add(5);
integerList.add(6);
...add as many as you like the list will grow as needed.
 
  • #10
haki said:
Vector<int> MyVector is not a valid code
Vector<Integer> is valid, since you cannot pass primitives into the <> tags.

Sorry, I've been doing C# exclusively for the past 6 months and i use primitives in generic collections all the time.
 

Similar threads

  • · Replies 2 ·
Replies
2
Views
2K
Replies
20
Views
2K
  • · Replies 10 ·
Replies
10
Views
3K
  • · Replies 7 ·
Replies
7
Views
3K
  • · Replies 5 ·
Replies
5
Views
3K
Replies
4
Views
3K
  • · Replies 3 ·
Replies
3
Views
4K
  • · Replies 28 ·
Replies
28
Views
4K
  • · Replies 46 ·
2
Replies
46
Views
9K
  • · Replies 1 ·
Replies
1
Views
2K