BASH Shell associates arrays to improve search efficiency

Source: Internet
Author: User
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
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.