There is an array that is already sorted. Now enter a number that requires it to be inserted into the array as it was originally.

Source: Internet
Author: User

public static void Main (string[] args) {
Int[] A = {1,3,5,7,9,19,29,70};
Int[] B = new int[a.length+1];
Scanner scan = new Scanner (system.in);
System.out.print ("Please enter a number:");
int insert = Scan.nextint ();
int n = 0;
When the number of inserts is less than the first number
if (Insert < a[0]) {
B[0] = insert;
for (int i = 1; i < b.length;i++) {
B[i] = a[i-1];
}
}else if (Insert > A[a.length-1]) {//when the number of inserts is greater than the last number

for (int i = 0; i < b.length-1;i++) {
B[i] = A[i];
}
B[b.length-1] = insert;
}else {
When the number of insertions is in the middle
int j = 0;
for (; J < A.length-1; J + +) {

if (Insert > A[j] && Insert < a[j+1]) {
n = j;
}
}
for (int k = 0;k <= n; k++) {
B[k]= A[k];
}
B[N+1] = insert;
for (int k = n+2; k <b.length;k++) {
B[K] = a[k-1];
}
}

for (int c = 0; c <b.length;c++) {
System.out.print (b[c]+ "");
}

}

}

There is an array that is already sorted. Now enter a number that requires it to be inserted into the array as it was originally.

Related Article

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.