Uploaded by Mr. Simp

insert and delete in min heap

advertisement
#include<stdio.h>
#include<stdlib.h>
int* insert(int* arr,int n){
int index,*new_arr,val;
printf("Enter the index\n");
scanf("%d",&index);
if(index>n){
printf("Invalid index for insertion\n");
return arr;}
printf("Enter the value of the new element\n");
scanf("%d",&val);
new_arr=(int *)malloc((n+1)*sizeof(int));
for(int i=0;i<=n;i++){
if(i<index)
new_arr[i]=arr[i];
else if(i==index)
new_arr[i]=val;
else
new_arr[i]=arr[i-1];
}return new_arr;
}
int* delete1(int* arr,int n){
if(n==0){
printf("The array is empty\n");
return arr;
}
int index,*new_arr,val;
printf("Enter the index\n");
scanf("%d",&index);
if(index>=n){
printf("Invalid index for deletion\n");
return arr;
}
val=arr[index];
new_arr =(int *)malloc((n-1)*sizeof(int));
for(int i=0;i<n;i++){
if(i<index)
new_arr[i]=arr[i];
else if(i==index)
continue;
else
new_arr[i-1]=arr[i];
}
printf("Removed element at the index %d with value %d",index,val);
return new_arr;
}
int main(){
int n,*arr,choice;
printf("Enter the size of array\n");
scanf("%d",&n);
arr=(int *)malloc(n*sizeof(int));
for(int i=0;i<n;i++){
printf("Enter the value of the element\n");
scanf("%d",&arr[i]);
}
while(1){
printf("1=Insert an element at an index\n");
printf("2=Delete an element from an index\n");
printf("3=Print the array\n");
printf("4=Exit\n");
scanf("%d",&choice);
printf("\n");
switch(choice){
case 1:
arr=insert(arr,n);
n++;
break;
case 2:
arr=delete1(arr,n);
n--;
break;
case 3:
for(int i=0;i<n;i++)
printf("%d",arr[i]);
break;
case 4:
exit(1);
}printf("\n");
}return 0;
}
Download