Array
Array
# Python code
arr = [10, 20, 30] # This array will store integer
arr2 = ['c', 'd', 'e'] # This array will store
characters
arr3 = [28.5, 36.5, 40.2] # This array will store
floating elements
Types of Array
• One-Dimensional Array
A one-dimensional array is a collection of elements of the same
data type stored in contiguous memory locations.
Example:
int[] scores = {10, 20, 30, 40, 50};
In this example, the scores array is a one-dimensional array that
stores five integer values.
In this array, the elements are indexed as follows:-
scores[0] refers to the first element, which is 10.-
scores[1] refers to the second element, which is 20.-
scores[2] refers to the third element, which is 30.-
scores[3] refers to the fourth element, which is 40.-
scores[4] refers to the fifth element, which is 50
Multi-Dimensional Arrays in Python
In Python, multi-dimensional arrays are represented using lists of lists.
Here's an example:
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(matrix)
# Output: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
import numpy as np
matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print(matrix)
# Output: [[1 2 3]
# [4 5 6]
# [7 8 9]]
• NumPy arrays provide a more efficient and convenient way to work with multi-dimensional
arrays, and are widely used in scientific computing and data analysis.
• Jagged Array
A jagged array is an array of arrays, where each inner array
can have a different length.
Example:int[][] jaggedArray = {
new int[] {1, 2, 3},
new int[] {4, 5},
new int[] {6, 7, 8, 9}
};
In this example, the jaggedArray array is a jagged array
that stores three inner arrays of different lengths.
Method of Arrays in Python
Python has several types of arrays:
1. Lists: Lists are the most common type of array in Python. They are denoted by
square brackets [] and are mutable, meaning they can be modified after
creation.
2. Tuples: Tuples are similar to lists but are immutable, meaning they cannot be
modified after creation. They are denoted by parentheses ().
3. Arrays: Python's array module provides a type of array that is similar to lists but
is more memory-efficient and provides additional functionality.
4. NumPy Arrays: NumPy (Numerical Python) is a library that provides support for
large, multi-dimensional arrays and matrices. NumPy arrays are the most
powerful and flexible type of array in Python.
Creating Arrays in Python
Here are some examples of creating arrays in Python:
Lists
my_list = [1, 2, 3, 4, 5]
print(my_list)
# Output: [1, 2, 3, 4, 5]
Tuples
my_tuple = (1, 2, 3, 4, 5)
print(my_tuple)
# Output: (1, 2, 3, 4, 5)
Arrays
import array
my_array = array.array('i', [1, 2, 3, 4, 5])
print(my_array)
# Output: array('i', [1, 2, 3, 4, 5])
NumPy Arrays
import numpy as np
my_array = np.array([1, 2, 3, 4, 5])
print(my_array)
# Output: [1 2 3 4 5]
Array Operations
• Indexing: accessing individual elements using their index.-
• Slicing: accessing a subset of elements using a range of indices.-
• Assignment: modifying individual elements or a subset of elements.-
• Iteration: iterating over the elements of the array.
• Insertion: Adding a new element to an array.
• Deletion: Removing an element from an array.
• Searching: Finding an element in an array.
• Sorting: Arranging elements of an array in a specific order.
• Append The Append operation is used to add a single element to the end of
an array.
• The Extend operation is used to add multiple elements to the end of an
array.
• Traversing an array means visiting each element one by one.
It's often done using loops.
for element in my_array:
print(element)
Array Operations in Python
Efficient memory usage: arrays store Fixed size: arrays have a fixed size that
elements in contiguous memory cannot be changed dynamically.-
locations, reducing memory overhead.-
Fast indexing: arrays allow for fast Insertion and deletion: inserting or
indexing and access to individual deleting elements in an array can be slow
elements and inefficient
Cache-friendly: arrays are cache-friendly,
reducing the number of cache misses.
Searching in Arrays
Linear Search
Linear search involves iterating through the array element by
element to find a specific value.
It's not the most efficient for large arrays.
https://www.cs.usfca.edu/~galles/visualization/Search.html
Dry Run:
Suppose we have the following array: Step 4: Repeat steps 2-3.
arr = [3, 5, 2, 7, 9, 1, 4] arr = [3, 5, 2, 7, 9, 1, 4]
We want to find the index of the element 7 using Linear Search. index = 2
target = 7
Step 1: Start at the beginning of the array. current = 2
arr = [3, 5, 2, 7, 9, 1, 4] match? No
index = 0
- If the loop completes without finding the target element, this line
returns -1 to indicate that the element was not found.
arr = [3, 5, 2, 7, 9, 1, 4]
target = 7
index = linear_search(arr, target)
print(index)
# Output: 3
target = 10
index = linear_search(arr, target)
print(index)
# Output: -1
Binary Search
• Binary Search is an efficient algorithm for finding an item from
a sorted list of items.
• It works by repeatedly dividing in half the portion of the list
that could contain the item, until you've narrowed down the
possible locations to just one
Example : Suppose we have the following list of Pass 2:
numbers: 1. Compare 2 and 5. Since 2 < 5, no swap.
[5, 2, 8, 3, 1, 6, 4] 2. Compare 5 and 3. Since 5 > 3, swap them.
We want to sort this list using Bubble Sort. - [2, 3, 5, 1, 6, 4, 8]
Pass 1: 3. Compare 5 and 1. Since 5 > 1, swap them.
1. Compare 5 and 2. Since 5 > 2, swap them. - [2, 3, 1, 5, 6, 4, 8]
- [2, 5, 8, 3, 1, 6, 4] 4. Compare 5 and 6. Since 5 < 6, no swap.
2. Compare 5 and 8. Since 5 < 8, no swap. 5. Compare 6 and 4. Since 6 > 4, swap them.
3. Compare 8 and 3. Since 8 > 3, swap them. - [2, 3, 1, 5, 4, 6, 8]
- [2, 5, 3, 8, 1, 6, 4] 6. Compare 6 and 8. Since 6 < 8, no swap.
4. Compare 8 and 1. Since 8 > 1, swap them.
- [2, 5, 3, 1, 8, 6, 4] Pass 3:
5. Compare 8 and 6. Since 8 > 6, swap them. 1. Compare 2 and 3. Since 2 < 3, no swap.
- [2, 5, 3, 1, 6, 8, 4] 2. Compare 3 and 1. Since 3 > 1, swap
6. Compare 8 and 4. Since 8 > 4, swap them. them. - [2, 1, 3, 5, 4, 6, 8]
- [2, 5, 3, 1, 6, 4, 8] 3. Compare 3 and 5. Since 3 < 5, no swap
4. Compare 5 and 4. Since 5 > 4, swap
them. - [2, 1, 3, 4, 5, 6, 8]
5. Compare 5 and 6. Since 5 < 6, no swap.
6. Compare 6 and 8. Since 6 < 8, no swap.
Pass 4:
1. Compare 2 and 1. Since 2 > 1, swap them.
- [1, 2, 3, 4, 5, 6, 8]
2. Compare 2 and 3. Since 2 < 3, no swap.
3. Compare 3 and 4. Since 3 < 4, no swap.
4. Compare 4 and 5. Since 4 < 5, no swap.
5. Compare 5 and 6. Since 5 < 6, no swap.
6. Compare 6 and 8. Since 6 < 8, no swap.
No more swaps are needed, and the list is
sorted.
Binary Search Implementation in Python:
- function named binary_search that takes two parameters:
- arr: the sorted list of elements to search through.
- target: the element to search for.
def binary_search(arr, target):
This line initializes two pointers, left and right,
left, right = 0, to the start and end indices of the arr list,
len(arr) - 1 Binary Search Loop
while left <= right: while left <= right:-
This line starts a while loop that continues until the left
mid = (left + right) / 2 pointer is greater than the right pointer.
if arr[mid] == target: - This line calculates the middle index mid of the current
return mid range [left, right].
elif arr[mid] < target: - If the middle element arr[mid] is less than the target,
left = mid + 1 the left pointer is updated to mid + 1.-
- If the middle element arr[mid] is greater than the
else: target, the right pointer is updated to mid - 1.
right = mid - 1 If the while loop completes without finding the target,
return -1 # Target not found the function returns -1
to indicate that the target was not found.
Here's an example usage of the Binary Search function:
arr = [2, 5, 8, 12, 16, 23, 38, 56, 72, 91]
target = 23
index = binary_search(arr, target)
print(index)
# Output: 5
target = 10
index = binary_search(arr, target)
print(index)
# Output: -1
Bubble Sort
Bubble sort repeatedly steps through the list, compares adjacent elements, and swaps them if
they are in the wrong order.
The pass through the list is repeated until the list is sorted.
- This line defines a function named bubble_sort that takes
def bubble_sort(arr): one parameter:
- - arr: the list of elements to be sorted.
n = len(arr)
gets the length of the arr list and assigns it to the variable n.
- This line starts an inner loop that iterates from the first element to the `(n-i-1)`th element
for j in range(n - 1 - i):
- .- The loop variable j represents the current index being compared.
if arr[j] > arr[j + 1]: - This line compares the current element arr[j] with the next element arr[j+1].
- If the current element is greater than the next element,
- the two elements are swapped.
arr[j], arr[j + 1] = arr[j + 1], arr[j]
https://www.w3schools.com/dsa/dsa_algo_bubblesort.php
Example: Pass 2:
Suppose we have the following list of numbers: 1. Compare 34 and 25. Since 34 > 25, swap them.
- List after pass 2: [25, 34, 12, 22, 11, 64, 90]
[64, 34, 25, 12, 22, 11, 90]
We want to sort this list using Bubble Sort. 2. Compare 34 and 12. Since 34 > 12, swap them.
- List after pass 2: [25, 12, 34, 22, 11, 64, 90]
Pass 1:
1. Compare 64 and 34. Since 64 > 34, swap them. 3. Compare 34 and 22. Since 34 > 22, swap them.
- List after pass 1: [34, 64, 25, 12, 22, 11, 90] - List after pass 2: [25, 12, 22, 34, 11, 64, 90]
2. Compare 64 and 25. Since 64 > 25, swap them. 4. Compare 34 and 11. Since 34 > 11, swap them.
- List after pass 1: [34, 25, 64, 12, 22, 11, 90] - List after pass 2: [25, 12, 22, 11, 34, 64, 90]
3. Compare 64 and 12. Since 64 > 12, swap them. 5. Compare 34 and 64. Since 34 < 64, no swap.
- List after pass 1: [34, 25, 12, 64, 22, 11, 90]
4. Compare 64 and 22. Since 64 > 22, swap them. Pass 3:
- List after pass 1: [34, 25, 12, 22, 64, 11, 90] 1. Compare 25 and 12. Since 25 > 12, swap them.
5. Compare 64 and 11. Since 64 > 11, swap them. - List after pass 3: [12, 25, 22, 11, 34, 64, 90]
- - List after pass 1: [34, 25, 12, 22, 11, 64, 90] 2. Compare 25 and 22. Since 25 > 22, swap them.
6. Compare 64 and 90. Since 64 < 90, no swap - List after pass 3: [12, 22, 25, 11, 34, 64, 90]
3. Compare 25 and 11. Since 25 > 11, swap them.
- List after pass 3: [12, 22, 11, 25, 34, 64, 90]
4. Compare 25 and 34. Since 25 < 34, no swap.
Pass 4:
1. Compare 12 and 22. Since 12 < 22, no swap.
2. Compare 22 and 11. Since 22 > 11, swap them.
- List after pass 4: [12, 11, 22, 25, 34, 64, 90]
3. Compare 22 and 25. Since 22 < 25, no swap.
4. Compare 25 and 34. Since 25 < 34, no swap.
Pass 5:
1. Compare 12 and 11. Since 12 > 11, swap them.
- List after pass 5: [11, 12, 22, 25, 34, 64, 90]
2. Compare 12 and 22. Since 12 < 22, no swap.
3. Compare 22 and 25. Since 22 < 25, no swap.
4. Compare 25 and 34. Since 25 < 34, no swap.
Pass 6:
No swaps needed.
The final sorted list is:[11, 12, 22, 25, 34, 64, 90]
This example illustrates how Bubble Sort works by repeatedly
iterating through the list, comparing adjacent elements, and
swapping them if necessary. The process continues until the list is
sorted.
Quick Sort
Quick sort is a divide-and-conquer algorithm that selects a
"pivot" element and partitions the other elements into two
sub-arrays, according to whether they are less than or
greater than the pivot.
def quick_sort(arr): - This line checks if the length of the arr list is less than or
equal to 1.
if len(arr) <= 1: - - If true, the function returns the original list, as it is
already sorted.
return arr
- This line selects a pivot element from the arr list.
pivot = arr[len(arr) // 2] - - The pivot is chosen as the middle element of the list.
left = [x for x in arr if x < pivot] - These lines partition the arr list into three sublists:
- - left: elements less than the pivot.
middle = [x for x in arr if x == pivot]
- - middle: elements equal to the pivot.
right = [x for x in arr if x > pivot]
- - right: elements greater than the pivot.
- This line recursively calls the quick_sort function
return quick_sort(left) + middle + quick_sort(right)
on the left and right sublists
- .- The sorted left and right sublists are
concatenated with the middle sublist to produce
https://www.w3schools.com/dsa/dsa_algo_quicksort.php the final sorted list.
arr = [3, 6, 8, 10, 1, 2, 1]
arr = quick_sort(arr)
print(arr)
# Output: [1, 1, 2, 3, 6, 8, 10]
Suppose we have the following list of numbers:
arr = [5, 2, 9, 1, 7, 3]
We'll go through the Quick Sort algorithm step by step.
Step 1: Choose a Pivot
We select the middle element of the list as the pivot:
pivot = arr[3] = 1
Step 2: Partition the List
We partition the list into three sublists:-
left: elements less than the pivot (1)
middle: elements equal to the pivot (1)
right: elements greater than the pivot (1)
- left = [1]
- middle = []right = [5, 2, 9, 7, 3]
Step 3: Recursively Sort Sublists
We recursively call the Quick Sort function on the left and right
sublists:-
quick_sort(left) = [1]
-quick_sort(right) = [2, 3, 5, 7, 9]
Step 4: Combine Sorted Sublists
We combine the sorted left, middle, and right sublists:
arr = quick_sort(left) + middle + quick_sort(right)
arr = [1] + [] + [2, 3, 5, 7, 9]
arr = [1, 2, 3, 5, 7, 9]
The final sorted list is:arr = [1, 2, 3, 5, 7, 9]