Insert a number into the sorted array and insert the number to the appropriate position.

Source: Internet
Author: User

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 + "");

}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.