Name
: Iqtedar Alim Alave
ID
: 2312303042
COURSE
: CSE 225
SECTION
:
08
Main.c File:
// main.cpp
#include "SortedList.h"
#include <iostream>
int main() {
SortedList list; // Create a SortedList object
// Insert items
list.insert(30);
list.insert(15);
list.insert(45);
list.insert(20);
// Display the list
std::cout << "List after insertion: ";
list.display();
int item = 15; // Search for an item
int position = list.search(item);
if (position != -1) {
std::cout << "Item " << item << " found at index " << position << std::endl;
} else {
std::cout << "Item " << item << " not found.\n";
}
list.remove(45); // Remove an item
std::cout << "List after removing 45: ";
list.display();
list.remove(15);
std::cout << "List after removing 15: ";
list.display();
return 0;
}
SortedList.cpp File:
//SortedList.cpp
#include "SortedList.h"
#include <iostream>
SortedList::SortedList() {
size = 0; // initializing size to 0
}
// Insert item in sorted order
void SortedList::insert(int item) {
int i = size - 1;
// Shifting elements to the right to findout the correct position
while (i >= 0 && arr[i] > item) {
arr[i + 1] = arr[i];
i--;
}
arr[i + 1] = item; // Insert the item at the correct position
size++; // Increment the size
}
// Search for an item and return its index or -1 if not found
int SortedList::search(int item) {
for (int i = 0; i < size; i++) {
if (arr[i] == item) {
return i; // Item found
}
}
return -1; // Item not found
}
// Remove item from the list
void SortedList::remove(int item) {
int index = search(item); // Find index of the item
if (index != -1) {
// Shift elements to the left to remove the item
for (int i = index; i < size - 1; i++) {
arr[i] = arr[i + 1];
}
size--; // Decrease the size
} else {
std::cout << "Item not found! \n";
}
}
// Display the elements of the list
void SortedList::display() {
for (int i = 0; i < size; i++) {
std::cout << arr[i] << " ";
}
std::cout << std::endl;
}
SortedList.h File:
// SortedList.h
#ifndef SORTEDLIST_H
#define SORTEDLIST_H
class SortedList {
private:
int arr[100]; // fixed size array
int size; // keep track of the number of elements
public:
SortedList(); // constructor to initialize the list
void insert(int item); // method to insert item
int search(int item); // method to search for item
void remove(int item); // method to delete item
void display();
// method to display the list
};
#endif
Output :