DSA1 - Insert Delete Search - Eong Koungmeng

Eong Koungmeng - អ៊ឹង គួងម៉េង

Hot

Post Top Ad

Wednesday, 4 January 2023

DSA1 - Insert Delete Search

DSA - Insert Delete Search

Code in C++

#include <iostream>
void showElements(int arr[], int& countElement)
{
std::cout << "Elements in the array: ";
for (int i = 0; i < countElement; i++)
{
std::cout << arr[i] << " ";
}
std::cout << std::endl;
}
void insert(int arr[], int& countElement, int pos, int value)
{
int i = pos;
int temp =0;
while (i < countElement)
{
temp = arr[i];
arr[i] = value;
value = temp;
i++;
}
arr[i] = temp;
countElement++;
}
void deleteByPosition(int arr[], int& countElement, int pos)
{
int i = pos;
while (i < countElement)
{
arr[i] = arr[i + 1];
i++;
}
countElement--;
}
void deleteByValue(int arr[], int& countElement, int value)
{
int i = 0;
while (i < countElement)
{
if (arr[i] == value)
{
for (int j =i ; j < countElement; j++)
{
arr[j] = arr[j + 1];
}
countElement--;
}
else
{
i++;
}
}
}
int search(int arr[], int& countElement, int value, bool nonDuplicate)
{
if (nonDuplicate)
{
for (int i = 0; i < countElement; i++)
{
if (arr[i] == value)
{
return i;
}
}
return -1;
}
else
{
int count = 0;
for (int i = 0; i < countElement; i++)
{
if (arr[i] == value)
{
count++;
}
}
return count;
}
}
int main()
{
int arr[64] = {3,2,1,7,1,4,3,8,5};
int countElement = 10;
showElements(arr, countElement);
int value = 3;
std::cout << "The count of " << value << " in array is "
<< search(arr, countElement, value, false); //search duplicate for value = 3
std::cin.get();
}
view raw week2DSA.cpp hosted with ❤ by GitHub

No comments:

Post a Comment

Post Top Ad