Data Structure 11 (1)
Data Structure 11 (1)
INSERTION
PRESENTED BY
ANJALI SHARMA
WHAT IS INSERTION ?
Insertion is operation in which a new value is added at a particular
in an array.
Insertion an element at the “end” of a linear array can be easily
done provided the memory space allocated for the array is large
enough to accommodate the additional element.
Let A be a collection of data elements in the memory of the
computer. Insertion refers to the operation of adding elements to
the collection.
If an element is to the inserted in the middle of the array, then, on
the average, half of the elements must be moved downward to
new locations to accommodate the new elements and keep the
order of the other elements.
Consider the list given below:
Price 0 1 2 3 4
Items: 10 20 30 40 50
Now the item 15 is to be inserted in position 1
First move item 50 from position 4 to position 5
Then move item 40 from position 3 to position 4
Then move item 30 from position 2 to position 3
Then move item 20 from position 1 to position 2
Now position 1 becomes vacant.
INSERTION AT THE BEGINNING
OF AN ARRAY
#INCLUDE <STDIO.H>
#DEFINE MAX 5
VOID MAIN() {
INT ARRAY[MAX] = {1, 2, 4, 5};
INT N = 4; // NUMBER OF ELEMENTS IN ARRAY
INT I = 0; // LOOP VARIABLE
INT INDEX = 2; // INDEX LOCATION TO INSERT NEW VALUE
INT VALUE = 3; // NEW DATA ELEMENT TO BE INSERTED
// print array before insertion
printf("Printing array before insertion −\n");
// print to confirm
printf("Printing array after insertion −\n");
#INCLUDE <STDIO.H>
#DEFINE MAX 5
VOID MAIN() {
INT ARRAY[MAX] = {1, 2, 4, 5};
INT N = 4; // NUMBER OF ELEMENTS IN ARRAY
INT I = 0; // LOOP VARIABLE
INT INDEX = 1; // INDEX LOCATION AFTER WHICH VALUE WILL BE INSERTED
INT VALUE = 3; // NEW DATA ELEMENT TO BE INSERTED
// print array before insertion
printf("Printing array before insertion −\n");
// print to confirm
printf("Printing array after insertion −\n");
#INCLUDE <STDIO.H>
#DEFINE MAX 5
VOID MAIN()
{
INT ARRAY[MAX] = {1, 2, 4, 5};
INT N = 4; // NUMBER OF ELEMENTS IN ARRAY
INT I = 0; // LOOP VARIABLE
INT INDEX = 3; // INDEX LOCATION BEFORE WHICH VALUE WILL BE INSERTED
// print array before insertion
printf("Printing array before insertion −\n");
for(i = 0; i < N; i++) {
printf("array[%d] = %d \n", i, array[i]);
}
// now shift rest of the elements downwards
for(i = N; i >= index + 1; i--) {
array[i + 1] = array[i];
}
// add new element at first position
array[index + 1] = value;
// print to confirm
printf("Printing array after insertion −\n");