Join Regular Classroom : Visit ClassroomTech

Data Structure – codewindow.in

Related Topics

Data Structure

#include <stdio.h>

int linearSearch(int arr[], int n, int x) {
   for (int i = 0; i < n; i++) {
      if (arr[i] == x) {
         return i;
      }
   }
   return -1;
}

int main() {
   int arr[] = {2, 5, 8, 12, 16};
   int n = sizeof(arr) / sizeof(arr[0]);
   int x = 8;
   int result = linearSearch(arr, n, x);
   if (result == -1) {
      printf("Element is not present in the array");
   } else {
      printf("Element is present at index %d", result);
   }
   return 0;
}

In this example, the linearSearch function takes three arguments: the array to search, the length of the array, and the element to search for. The function then traverses the array, comparing each element with the search element. If the search element is found, the function returns the index of that element. If the search element is not found, the function returns -1. The main function initializes an array, searches for an element, and prints the result.

int binary_search(int arr[], int n, int key) {
    int lower_bound = 0;
    int upper_bound = n - 1;
    int middle_index;

    while (lower_bound <= upper_bound) {
        middle_index = (lower_bound + upper_bound) / 2;
        if (arr[middle_index] == key) {
            return middle_index;
        }
        else if (arr[middle_index] < key) {
            lower_bound = middle_index + 1;
        }
        else {
            upper_bound = middle_index - 1;
        }
    }

    return -1;
}

In this code, arr is the sorted array, n is the size of the array, and key is the search key. The function returns the index of the search key if it is found in the array, or -1 if it is not found.

array[start:end]

where start is the index of the first element to include in the slice (inclusive) and end is the index of the first element to exclude from the slice (exclusive).

For example, consider the following list of integers:

numbers = [1, 2, 3, 4, 5]

To extract a slice of the list containing the elements from index 1 to 3 (excluding the element at index 3), we would use the following code:

slice = numbers[1:3]

This would create a new list containing the elements [2, 3].

We can also use slicing to extract elements from the beginning or end of an array. For example, to extract the first three elements of the list numbers, we would use:

slice = numbers[:3]

This would create a new list containing the elements [1, 2, 3].

Similarly, to extract the last two elements of the list numbers, we would use:

slice = numbers[-2:]

This would create a new list containing the elements [4, 5].

# Declaring and initializing a list of integers
my_list = [1, 2, 3, 4, 5]

# Declaring and initializing a list of strings
my_list2 = ['apple', 'banana', 'cherry']

We can also declare an empty list and then add elements to it later:

# Declaring an empty list
my_list3 = []

# Adding elements to the list
my_list3.append('dog')
my_list3.append('cat')
my_list3.append('fish')

In this example, we declared an empty list my_list3 and used the append() method to add elements to it.

arr = [10, 20, 30, 40, 50]
print(arr[0]) # output: 10
print(arr[2]) # output: 30

You can also use negative indexing to access elements from the end of the array. For example, arr[-1] gives you the last element, arr[-2] gives you the second to last element, and so on.

arr = [1, 2, 3]
arr.append(4)
print(arr) # Output: [1, 2, 3, 4]
  1. Using the insert() method: The insert() method adds an element at a specific index of the array.

arr = [1, 2, 3]
arr.insert(1, 4)
print(arr) # Output: [1, 4, 2, 3]
  1. Using the extend() method: The extend() method adds multiple elements to the end of the array.

arr = [1, 2, 3]
arr.extend([4, 5, 6])
print(arr) # Output: [1, 2, 3, 4, 5, 6]
  1. Using the + operator: The + operator can be used to concatenate two arrays.

arr1 = [1, 2, 3]
arr2 = [4, 5, 6]
arr3 = arr1 + arr2
print(arr3) # Output: [1, 2, 3, 4, 5, 6]
# Initialize an array
fruits = ['apple', 'banana', 'orange', 'mango']

# Remove an element from the array
fruits.remove('orange')

# Print the modified array
print(fruits) # Output: ['apple', 'banana', 'mango']

You can also remove an element from an array using the del keyword and the index of the element. Here is an example:

# Initialize an array
fruits = ['apple', 'banana', 'orange', 'mango']

# Remove an element from the array
del fruits[2]

# Print the modified array
print(fruits) # Output: ['apple', 'banana', 'mango']

In this example, the del keyword is used to remove the element at index 2 (which is the third element) from the array.

arr = [1, 2, 3, 4, 5]
reversed_arr = arr[::-1]
print(reversed_arr)   # Output: [5, 4, 3, 2, 1]
  1. Using the reverse() method:

arr = [1, 2, 3, 4, 5]
arr.reverse()
print(arr)   # Output: [5, 4, 3, 2, 1]
  1. Using the reversed() function:

arr = [1, 2, 3, 4, 5]
reversed_arr = list(reversed(arr))
print(reversed_arr)   # Output: [5, 4, 3, 2, 1]
arr = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]

# Sort the array in ascending order
arr.sort()

print(arr) # Output: [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]

If you want to sort the array in descending order, you can use the reverse parameter of the sort() method, like this:

arr = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]

# Sort the array in descending order
arr.sort(reverse=True)

print(arr) # Output: [9, 6, 5, 5, 5, 4, 3, 3, 2, 1, 1]

Alternatively, you can use the sorted() function to create a new sorted list without modifying the original array. Here’s an example:

arr = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]

# Create a new sorted list without modifying the original array
sorted_arr = sorted(arr)

print(sorted_arr) # Output: [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]
arr = [1, 2, 3, 4, 5]

if 3 in arr:
    print("3 is present in the array")
else:
    print("3 is not present in the array")

Output:

3 is present in the array

You can also use the index() method to find the index of the first occurrence of an element in an array.

Here’s an example:

arr = [1, 2, 3, 4, 5]

index = arr.index(3)
print("The index of 3 in the array is", index)

Output:

The index of 3 in the array is 2

Note that if the element is not present in the array, the index() method will raise a ValueError. You can handle this by using a tryexcept block.

      

Go through our study material. Your Job is awaiting.

Recent Posts
Categories