3 - Arrays and Functions
3 - Arrays and Functions
Explanation
1. One-Dimensional Arrays
• A one-dimensional array is a collection of elements
(usually of the same data type) that are stored in
contiguous memory locations.
• The elements in an array are accessed using indices,
which start from 0.
• For example, an array of integers might look like: int
arr[5] = {10, 20, 30, 40, 50};, where arr[0] = 10, arr[1] =
20, etc.
2. Array Manipulation
• Insertion: Adding an element to the array, typically
involves shifting elements to create space.
• Deletion: Removing an element from the array may
require shifting elements to close the gap.
• Accessing: Fetching the value at a specific index, like
arr[3] to get the 4th element.
• Updating: Modifying the value of an element in the
array by directly accessing its index.
3. Sorting
• Sorting arranges elements in a specific order, either
ascending or descending.
• Common sorting algorithms:
o Bubble Sort: Repeatedly swaps adjacent elements
if they are in the wrong order.
o Selection Sort: Selects the smallest (or largest)
element and swaps it with the first unsorted
element.
o Insertion Sort: Builds the sorted array one element
at a time by inserting each new element into its
correct position.
o Quick Sort: Uses a pivot to partition the array into
subarrays and sorts them recursively.
o Merge Sort: Divides the array into halves,
recursively sorts them, and then merges the sorted
halves.
4. Searching
• Searching algorithms help locate an element in the array.
o Linear Search: Iterates through the array element
by element to find the desired value.
o Binary Search: Efficient algorithm for sorted arrays.
It divides the search interval in half repeatedly,
discarding one half after each comparison.