Array
Array
and Sorting
Introduction to Arrays
An array is a data structure that can hold a collection of elements of the same data type.
In Python, arrays are implemented using lists.
my_array = [1, 2, 3, 4, 5]
Traversing Arrays
Traversing an array means visiting each element one by one.
It's often done using loops.
Array Operations
Common array operations include adding, removing, and modifying elements.
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.
def linear_search(arr, target):
for i, element in enumerate(arr):
if element == target:
return i
return -1 # Target not found
https://www.cs.usfca.edu/~galles/visualization/Search.html
Binary Search
Binary search is a more efficient way to search for a value in a sorted array.
It repeatedly divides the search interval in half.
Sorting Arrays
Bubble Sort
Bubble sort repeatedly steps through the list, compares adjacent elements, and swaps
them if they are in the wrong order.
def bubble_sort(arr):
n = len(arr)
for i in range(n - 1):
for j in range(n - 1 - i):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
https://www.w3schools.com/dsa/dsa_algo_bubblesort.php
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):
if len(arr) <= 1:
return arr
pivot = arr[len(arr) // 2]
left = [x for x in arr if x < pivot]
middle = [x for x in arr if x == pivot]
right = [x for x in arr if x > pivot]
return quick_sort(left) + middle + quick_sort(right)
https://www.w3schools.com/dsa/dsa_algo_quicksort.php