3 Arrays

You might also like

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 31

Lovely Professional University, Punjab

Data Structures
Lecture : Linear Array
Contents
• Basic Terminology
• Linear Array
• Memory Representation of Linear Array
• Traversing Array
• Insertion and Deletion in Array
• Sorting (Bubble Sort)
• Searching (Linear Search and Binary Search)
• Review Questions
Basic Terminology
• Linear Data Structures: A data structure is said to be linear if its
elements form a sequence or a linear list.

• Linear Array: is a list of a finite number n of homogeneous data


elements such that:

(a) the elements of the array are referenced by an index set


consisting of n consecutive numbers.

(b) the elements of the array are stored respectively in


successive memory locations.
Key Terms
• Size / Length of Array
• Index of Array
• Upper bound and Lower bound of Array
Memory Representation of Arrays
19 5 42 18 199

1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
Traversing Linear Array
• Suppose we have to count the number of element is an array
or print all the elements of array.

• Algorithm 1: (Using While Loop)

1. [Initialize Counter.] Set K = LB.


2. Repeat Step 3 and 4 while K<= UB.
3. [Visit Element.] Apply PROCESS to A[K].
4. [Increase Counter.] Set K = K+1.
[End of Step 2 Loop.]
5. Exit.
Algorithm 2: (Using for loop)

1. Repeat for K = LB to UB
Apply PROCESS to A[K].
[ End of Loop.]
2. Exit.

Question.1: Find the Number of elements in an array which are


greater than 25.

Question 2: Find out the sum of all the two digit numbers in an
array.
Insertion and Deletion in an Array
• Two types of insertion are possible:
• Insertion at the end of array
• Insertion in the middle of the array
Insertion into a Linear Array
• Algorithm: (Insertion of an element ITEM into Kth position in
a Linear Array A)

1. [Initialize Counter.] Set J = N.


2. Repeat Steps 3and 4 while J >= K.
3. [Move Jth element downward] Set A[J+1] = A[J].
4. [Decrease Counter.] Set J = J-1.
[End of Step 2 loop]
5. [Insert element.] Set A[K] = ITEM.
6. [Reset N] N = N+1.
7. Exit
Deletion into a Linear Array
Algorithm: (Delete Kth element from Linear Array A)

1. Repeat for J = K to N-1.


2. [Move (J+1)th element upward] Set A[J] = A[J+1].
[End of loop.]
3. [Reset the number of elements N] Set N = N-1.
4. Exit
Merging Algorithm

• Suppose A is a sorted list with r elements and B is a sorted list


with s elements. The operation that combines the element of A
and B into a single sorted list C with n=r + s elements is called
merging.

11
Merging Algorithm
 Algorithm: Merging (A, R,B,S,C)
Here A and B be sorted arrays with R and S elements
respectively. This algorithm merges A and B into an array
C with N=R+ S elements
 Step 1: Set NA=0, NB=0 and NC=0
 Step 2: Repeat while NA < R and NB < S:
if A[NA] ≤ B[NB], then:
Set C[NC] = A[NA]
Set NA = NA +1
else
Set C[NC] = B[NB]
Set NB = NB +1
[End of if structure]
Set NC= NC +1
[End of Loop]

12
Merging Algorithm
Step 3: If NA >=R, then:
Repeat while NB < S:
Set C[NC] = B[NB]
Set NB = NB+1
Set NC = NC +1
[End of Loop]
else
Repeat while NA < R:
Set C[NC] = A[NA]
Set NC = NC + 1
Set NA = NA +1
[End of loop]
[End of if structure]
Step 4: Return C[NC]
13
 #include <stdio.h>
Merge Program
 int main() {
 void merge_arrays(int A[], int R, int B[], int S, int C[]) {
 int NA = 0, NB = 0, NC = 0;  int A[] = {1, 3, 5, 7, 9};
 int R = sizeof(A) / sizeof(A[0]);
 while (NA < R && NB < S) {
 if (A[NA] <= B[NB]) {
 C[NC] = A[NA];  int B[] = {2, 4, 6, 8, 10};
 NA++;  int S = sizeof(B) / sizeof(B[0]);
 } else {
 C[NC] = B[NB];
 NB++;
 int C[R + S];
 }
 NC++;  merge_arrays(A, R, B, S, C);
 }

 while (NA < R) {  printf("Merged and sorted array: ");


 C[NC] = A[NA];  for (int i = 0; i < R + S; i++) {
 NA++;
  printf("%d ", C[i]);
NC++;
 }  }
 printf("\n");
 while (NB < S) {
 C[NC] = B[NB];
 NB++;  return 0;
 NC++;  }
 }
 }
14
Merging Algorithm
• Complexity of merging: The input consists of the total number
n=r+s elements in A and B. Each comparison assigns an
element to the array C, which eventually has n elements.
Accordingly, the number f(n) of comparisons cannot exceed n:
f(n) ≤ n = O(n)

15
Searching
1. Linear Search:
• Compares the item of interest with each element of Array
one by one.
• Traverses the Array sequentially to locate the desired
item.
Linear Search Algorithm
• LINEAR (DATA, N, ITEM, LOC)

1. [Insert ITEM at the end of DATA] Set Data [N+1]= ITEM.


2. [Initialize Counter] Set LOC=1.
3. [Search for ITEM.]
Repeat while DATA [LOC] != ITEM
Set LOC = LOC +1.
[End of loop.]
4. [Successful?] if LOC = N + 1, then Set LOC = 0.
5. Exit.
Binary Search
• BINARY ( DATA, LB, UB, ITEM, LOC )
1. [Initialize Segment Variables]
Set BEG = LB, END = UB and MID = INT ((BEG+END)/2).
2. Repeat Steps 3 and 4 while BEG <= END and DATA [MID] != ITEM.
3. If ITEM < DATA[MID], then:
Set END = MID - 1.
Else:
Set BEG = MID + 1.
[End of if Structure.]
4. Set MID = INT ((BEG+END)/2).
[End of Step 2 Loop.]
5. If DATA [MID] = ITEM, then: LOC=MID
Else:
Set LOC = NULL.
[End of if structure.]
6. Exit.
Binary Search Program
• #include <stdio.h>
int main() {
• int binary_search(int data[], int size, int item) {
• int data[] = {1, 3, 5, 7, 9, 11, 13, 15};
• int beg = 0;
• int size = sizeof(data) / sizeof(data[0]);
• int end = size - 1;
• int item = 7;
• int mid;

• while (beg <= end) {


• int index = binary_search(data, size, item);
• mid = (beg + end) / 2;

if (data[mid] == item) {
• if (index != -1) {
• return mid; // Element found, return its index
• printf("Element %d found at index %d\n",
• } else if (item < data[mid]) {
item, index);
• end = mid - 1; // Search in the left half
• } else {
• } else {
Limitations of Binary Search
• Although the complexity of Binary Search is
O (log n), it has some limitations:
1. the list must be sorted
2. one must have direct access to the middle element in any
sublist.
Selection Sort
Selection Sort
Selection Sort
// Selection sort in C
// function to print an array

void printArray(int array[], int size) {


#include <stdio.h> for (int i = 0; i < size; ++i) {

// function to swap the the position of two elements printf("%d ", array[i]);

void swap(int *a, int *b) {


}

printf("\n");
int temp = *a;
}
*a = *b;

*b = temp;
// driver code
}
int main() {
void selectionSort(int array[], int size) { int data[] = {20, 12, 10, 15, 2};

for (int step = 0; step < size - 1; step++) { int size = sizeof(data) / sizeof(data[0]);

int min_idx = step;


selectionSort(data, size);

printf("Sorted array in Acsending Order:\n");


for (int i = step + 1; i < size; i++) {
printArray(data, size);
// To sort in descending order, change > to < in this line.
}
// Select the minimum element in each loop.
Insertion Sort
Insertion Sort
Insertion Sort
// Insertion sort in C
// Function to print an array

void printArray(int array[], int size) {


#include <stdio.h>

void insertionSort(int array[], int size) {


for (int i = 0; i < size; i++) {

for (int step = 1; step < size; step++) { printf("%d ", array[i]);

int key = array[step]; }

int j = step - 1;
printf("\n");
// Compare key with each element on the left of it until an
}
element smaller than

// it is found.

// For descending order, change key<array[j] to // Driver code


key>array[j].
int main() {
while (key < array[j] && j >= 0) {
int data[] = {9, 5, 1, 4, 3};
Bubble Sort
Bubble Sort
Bubble Sort
Bubble Sort
#include <stdio.h> // print array
void printArray(int array[], int size) {
// perform the bubble sort for (int i = 0; i < size; ++i) {
void bubbleSort(int array[], int size) { printf("%d ", array[i]);
// loop to access each array element
}
for (int step = 0; step < size - 1; ++step) { printf("\n");
}
// loop to compare array elements
for (int i = 0; i < size - step - 1; ++i) { int main() {
int data[] = {-2, 45, 0, 11, -9};
// compare two adjacent elements
// change > to < to sort in descending order
if (array[i] > array[i + 1]) {
// find the array's length
int size = sizeof(data) / sizeof(data[0]);
// swapping occurs if elements
// are not in the intended order bubbleSort(data, size);
int temp = array[i];
array[i] = array[i + 1]; printf("Sorted Array in Ascending
array[i + 1] = temp; Order:\n");
}
}
printArray(data, size);
} }
}
Questions

You might also like