Hello,(adsbygoogle = window.adsbygoogle || []).push({});

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

**Physics Forums | Science Articles, Homework Help, Discussion**

The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

# Sorting an Array in Java

**Physics Forums | Science Articles, Homework Help, Discussion**