ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

Bash Array Element Search

Bash

Goal -- WPM

Ready
Exercise Algorithm Area
1#!/bin/bash
2
3# Function to find the index of an element in an array
4find_element_index() {
5local target_element="$1"
6shift # Remove the target element from arguments
7local array=($@) # Remaining arguments form the array
8local len=${#array[@]}
9local found_index=-1
10
11# Handle empty array edge case
12if [ "$len" -eq 0 ]; then
13echo "-1"
14return
15fi
16
17# Iterate through the array to find the element
18for (( i=0; i<$len; i++ )); do
19if [ "${array[$i]}" == "$target_element" ]; then
20found_index=$i
21break # Element found, exit loop
22fi
23done
24
25echo "$found_index"
26}
27
28# Example usage:
29# my_array=("apple" "banana" "cherry" "date")
30# index=$(find_element_index "cherry" "${my_array[@]}")
31# echo "Index of 'cherry': $index"
32# index_not_found=$(find_element_index "grape" "${my_array[@]}")
33# echo "Index of 'grape': $index_not_found"
Algorithm description viewbox

Bash Array Element Search

Algorithm description:

This Bash script provides a function `find_element_index` that searches for a given element within an array and returns its first occurrence's index. If the element is not present in the array, it returns -1. This is a common operation in data processing and scripting where you need to locate specific items within collections.

Algorithm explanation:

The `find_element_index` function searches for a `target_element` within a Bash array. It first captures the `target_element` and then uses `shift` to make the remaining arguments available as the `array`. It handles the edge case of an empty array by returning -1. The function iterates through the array using a `for` loop from index 0 up to `len-1`. Inside the loop, it compares the current array element `${array[$i]}` with the `target_element`. If a match is found, `found_index` is set to the current index `i`, and the loop is terminated using `break`. If the loop completes without finding the element, `found_index` remains -1. The time complexity is O(n) in the worst case (element not found or at the end), where n is the number of elements in the array, as it may need to check every element. The space complexity is O(1) as it only uses a few variables to store state. The loop boundaries are critical to ensure all elements are checked.

Pseudocode:

function find_element_index(target_element, array):
  if array is empty:
    return -1
  
  found_index = -1
  
  for i from 0 to length of array - 1:
    if array[i] equals target_element:
      found_index = i
      break
  
  return found_index