Preface
- The time complexity of determining whether an element exists in an array is generally O (N), because the common practice is to traverse the array and check whether the data to be searched exists.
- Here is a method for determining whether an element exists when the time complexity of key uniqueness is O (1 ).
- This method is often used in C language. Here we will introduce how to use the associated array and key value uniqueness in Shell syntax to improve script execution efficiency.
Requirement & Solution: Construct a keyword array and a search Array
# Construct the keyword array for num in 'seq 1 10' doelement [$ num] = "User _" $ numdone # construct the searched array for num in 'seq 1 100' dosearch [$ num] = "User _" $ numdone
O (n2) normal search
# Ordinary search method, time complexity O (n2) for E in $ {element [*]} dofor s in $ {search [*]} doif [$ e = $ s]; thenecho "find $ e" breakfidonedone
O (1) join array search
# Declare-A newsearchfor s in $ {search [*]} donewsearch [$ S] = 1 done # key value uniqueness, time complexity O (1) for E in $ {element [*]} doif [$ {newsearch [$ E]}-EQ 1]; thenecho "find $ e" fidone
Shell associates array subscript array elements through array subscript (array subscript can be an arithmetic expression, and the result must be an integer, however, this access method imposes restrictions when expressing some highly correlated data similar to PhP. Shell also provides an array that can use any string as a subscript to access array elements, this array is called an associated array. The joined array is also the essence of PHP. To define the joined array in shell, it must be declared. Declaration Syntax:
Declare-A array_name