After inserting an element into a sequential sequence, the sequence is still an array of sequential

Source: Internet
Author: User

/**

After inserting an element into an ordered array, the sequence is still a sequential array:

Idea: Find the insertion position of the element first

When inserting data, move the elements in the array back, then insert the element

*/

#include <stdio.h>

#define N 10

int main ()

{

After inserting an element into a sequential sequence, the sequence is still a sequential sequence:

int A[n] = {-1, 3, 6, 9, 13, 22, 27, 32, 49};

int insertval;

int insertloc;

scanf ("%d", &insertval);

Find the inserted number in the array to get the position

for (int i = 0; i<9; i++) {

if (Insertval>a[i] && insertval<a[i+1]) {//The element in the sequence element

Insertloc = i+1;

Insert to this location (you need to place the value behind the position and insert the value)

for (Int J =n-1; j>i+1; j--) {

A[J] = a[j-1];

}

A[i+1] =insertval;

}else if (Insertval < a[n-10]) {//The element is placed in the first position

Insertloc = n-10;

for (int j = n-1; j>0; j--) {

A[J] = a[j-1];

}

A[0] = Insertval;

}else if (Insertval > A[n-2]) {//The element is on the last side

Insertloc = n-1;

A[n-1] = Insertval;

}

}

Output

for (int i = 0; I <n; i++) {

printf ("%d", a[i]);

}

printf ("\ n");

return 0;

}

After inserting an element into a sequential sequence, the sequence is still an array of sequential

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.