Sparse array in C++In this article, we will discuss the sparse array in C++ with its example. A sparse array represents a data array in which many of the elements contain a value of zero. As a result, in a full array, the majority of the components have non-zero values or are "full" of numbers. In computer data handling, a sparse array may be handled differently from a dense array. Sparse array properties:
Example: [[1 0 1], [0 2 0], [0 3 0]] Why a sparse array is preferred over a simple array for storing elements:Storage: When there are a majority of zero elements and the fewest non-zero elements, we choose a sparse array instead of a simple array since it uses a smaller amount of memory to store all of the elements. Something other than zero elements is stored in the sparse array. Computation Time: Because we only keep non-zero components in the sparse array, traversing just non-zero components takes less time for computation. Sparse Array Representation:There are two ways to express sparse arrays:
1. Representation of an Array: A sparse array is represented by a 2-D array with three rows: Row, Column, and Value. Row: The starting position of the row containing non-zero elements. Column: The number that represents the index of the column containing the non-zero element. Value: A non-zero value found in the (Row, Columns) index. 2. Representation of Linked Lists:Each of the nodes in a sparse array is represented by four fields: Row, Column, Value, and Next node. Row: It is the starting position of the row containing non-zero elements. Column: The value of the index of the column containing the non-zero element. Value: A non-zero value found in the (Row, Column) index. Next Node: It saves a subsequent node's address. Algorithm Filename: SparseArray.cpp Output: The given matrix is: 1 0 9 3 0 0 1 0 0 The total number of zeros in the given array are 5 The given array is a sparse array.
Next TopicStd::allocator_arg in C++
|