I recently read the previous book "Java development practices" written by Li Xinghua. Every time I read a previous book, I got a different harvest. Many things I didn't understand before, now I suddenly realized it;
This question is the exercise in the book. I didn't give a reference to the answer. I didn't find a good question on the Internet. I sent it up. I feel that this algorithm can be optimized better. I hope you can give me some advice.
// Insert a number into the sorted array and insert the number to the appropriate position.
IntIntarr [] = {11, 22, 33, 44, 55, 66, 77 };
IntInsertnum = 34;
// Locate the location to insert
IntInsertindex = 0;
For(IntI = 0; I <intarr. length; I ++ ){
If(Insertnum <intarr [I]) {
Insertindex = I;
Break;
}
}
// Place insertnum into the position to be inserted, and then move each of the following parts backward to a badge
IntIntarr1 [] =New int[Intarr. Length + 1];
For(IntI = 0; I <intarr1.length; I ++ ){
If(I> = insertindex ){
If(I = insertindex) // This is only once.
Intarr1 [I] = insertnum;
If(I + 1 <intarr1.length) // I + 1 will cross the border and add judgment
Intarr1 [I + 1] = intarr [I];
}Else{
// Execute before insertion. Do not execute after insertion.
Intarr1 [I] = intarr [I];
}
}
// Cyclic output
For(IntI: intarr1 ){
System.Out. Print (I + "");
}