Home > Backend Development > C++ > body text

A data structure with n elements and with O(1) operations?

WBOY
Release: 2023-08-29 18:53:11
forward
1001 people have browsed it

A data structure with n elements and with O(1) operations?

Here we will see a data structure with n elements and O(1) operations. Therefore, the operation will take constant time to execute.

The data structure will hold n elements (from 0 to n-1). Data can be in any order. Insertion, deletion and search will take O(1) time.

To solve this problem we will use a boolean array. This will indicate whether the item exists at location i. 1 if the item exists, 0 otherwise.

Algorithm

Initialization(n)

begin
   fill all elements of the Boolean array as 0
end
Copy after login

Insertion(i)

begin
   set element at index i as 1(true)
end
Copy after login

Delete(i)

begin
set element at index i as 0(false)
end
Copy after login

Search(i)

begin
   return item at position i
end
Copy after login

Example

//initialization
void init(int n) {
   bool dataStructure[n];
   for (int i = 0; i<n; i++)
      dataStructure[i] = 0;
}
//Insertion
void insert(unsigned i) {
   dataStructure[i] = 1;
}
//Deletion
void delete(unsigned i) {
   dataStructure[i] = 0;
}
//Search
bool search(unsigned i) {
   return dataStructure[i];
}
Copy after login

The above is the detailed content of A data structure with n elements and with O(1) operations?. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template