DSA - Insert Delete Search
Code in C++
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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(); | |
} |
No comments:
Post a Comment