# How efficient is this code?

Hello

I have a fairly small code here that accepts an array from the user, asks them for a element and deletes that element(if present in the array).

``````/* Deletion in a array */
#include <iostream>
#define EXIT_FAILURE -1
#define EXIT_SUCCESS 0
using namespace std;
/* Function searches an array */
int BinarySearch(int * ARR, int SIZE, int ELEMENT)
{
int BEG_i = 0, MID_i, LAST_i = SIZE - 1;
while(BEG_i <= LAST_i)
{
MID_i = (BEG_i + LAST_i) / 2;
if(ARR[MID_i] == ELEMENT)
return MID_i;
else if(ARR[MID_i] < ELEMENT)
BEG_i = MID_i + 1;
else
LAST_i = MID_i - 1;
}
return -1;
}
/* Function deletes the required element */
int *Delete(int *ARR, int &SIZE, int index)
{
int temp_index;
ARR[index] = 0;
for(int I = index; I < SIZE - 1; I++)
{
ARR[I] = ARR[I + 1];
temp_index = I + 1;
}
SIZE--;
ARR[temp_index] = 0;
return ARR;
}
int main()
{
int *intArr= nullptr;
int arrSize, searchElement, index = 0;
cout << "\nEnter the size of the array: ";
cin >> arrSize;
intArr = new int[arrSize + 10];		/* Allocating a little extra memory in case of emergencies :D */
if(!intArr)
{
cerr << "\nOops! Something went wrong!" << endl;
system("pause");
exit(0);
}
cout << "\nEnter the array:-\n" << endl;
for(int I= 0; I < arrSize; I++)
{
cout << "Enter element : ";
cin >> intArr[I];
}

cout << "\nEnter element you want to delete: ";
cin >> searchElement;
index = BinarySearch(intArr, arrSize, searchElement);
if(index != -1)
{
Delete(intArr, arrSize, index);
}

else
{
cout << "\nElement \"" << searchElement << "\" not found in array!" << endl;
cout << endl;
system("pause");
delete[] intArr;
return EXIT_SUCCESS;
}
cout << "\nArray after deleting '" << searchElement << "' :-\n" << endl;
for(int I = 0; I < arrSize; I++)
{
cout << intArr[I] << " ";
}
cout << endl;
system("pause");
delete[] intArr;
return EXIT_SUCCESS;
}
``````

Can you tell me how efficient it is to use it in various situations? Or is it not practically usable in most cases? And what changes do you suggest I make in it(if any are required)?

Thanks nd Cheers!

Could you tell us what you are using this code for , what is the range of numbers and how many operations are you planning to perform?
Depending on the purpose you could considering using a linked list or using extra memory.

1 Like

1 thing i would like to point out is that…to use binary search…u need to sort the array first…!!

1 Like

@kunal361 You know CBSE classes XII had arrays chapter in its course and array operations are also a part of it. So, after a few major and minor changes, I am gonna use my code for deleting data from text or dat files for games, etc.

@kcahdog As far as my estimates, the range won’t be greater than 10000 or 50000.

//