UNIT II: Arrays and Linked Lists Detailed Academic Notes
ARRAYS
1. Definition:
An array is a collection of elements stored at contiguous memory locations. All elements are of the same data
type and can be accessed using an index.
2. Linear Arrays:
A linear array is a one-dimensional list where each element has a unique index starting from 0.
3. Arrays as ADT (Abstract Data Type):
Operations: Traverse, Insert, Delete, Search, Sort.
Properties: Fixed size, random access (O(1) time complexity).
4. Memory Representation:
If A is an array with base address BA and each element takes W bytes:
LOC(A[i]) = BA + i * W
5. Traversing:
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
6. Insertion (at position pos):
for (int i = n - 1; i >= pos; i--) {
arr[i + 1] = arr[i];
arr[pos] = value;
n++;
7. Deletion:
for (int i = pos; i < n - 1; i++) {
arr[i] = arr[i + 1];
n--;
8. Multi-Dimensional Arrays:
Example: int matrix[3][3];
Memory Address:
LOC(A[i][j]) = BA + ((i * number_of_columns) + j) * W
9. Sparse Matrix:
Matrix mostly filled with 0s. Stored using Triplet format:
Row | Col | Value
------------------
0 | 1 | 3
1 | 0 | 7
SEARCHING & SORTING
Linear Search:
int linearSearch(int arr[], int n, int key) {
for (int i = 0; i < n; i++) {
if (arr[i] == key)
return i;
return -1;
Binary Search (for sorted array):
int binarySearch(int arr[], int l, int r, int key) {
while (l <= r) {
int mid = l + (r - l) / 2;
if (arr[mid] == key) return mid;
else if (arr[mid] < key) l = mid + 1;
else r = mid - 1;
return -1;
Bubble Sort:
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
LINKED LISTS
1. Definition:
A linked list is a linear data structure where each element (node) contains data and a pointer to the next
node.
2. Singly Linked List:
struct Node {
int data;
struct Node* next;
};
Memory Allocation:
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
Traversal:
void printList(struct Node* head) {
while (head != NULL) {
printf("%d ", head->data);
head = head->next;
Insertion at beginning:
void insertFront(struct Node** head, int val) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = val;
newNode->next = *head;
*head = newNode;
Deletion:
void deleteNode(struct Node** head, int key) {
struct Node *temp = *head, *prev = NULL;
if (temp != NULL && temp->data == key) {
*head = temp->next;
free(temp);
return;
while (temp != NULL && temp->data != key) {
prev = temp;
temp = temp->next;
if (temp == NULL) return;
prev->next = temp->next;
free(temp);
Garbage Collection:
In C, use free() to release memory.
Doubly Linked List:
Each node has prev and next pointers.
struct DNode {
int data;
struct DNode* prev;
struct DNode* next;
};
Circular Linked List:
The last node points to the first node (head).
Header Linked List:
Contains a special header node before the actual data nodes.