- #1
pumas
- 15
- 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
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