02 Arrays Searching Sorting
02 Arrays Searching Sorting
the dimension
Examples:
int a[20], b[3], c[7];
Examples:
int a[4]={1, 3, 5, 2};
float b[3]={2.0, 5.5, 3.14};
char name[5]= {‘N’, ‘a’, ‘o’, ‘m’ , ‘i’};
#include<stdio.h>
#define SIZE 10
int main() {
int x[10] = {4, 3, 7, -1, 7, 2, 0, 4, 2, 13};
int i, sum=0;
float av;
for(i=0, i<SIZE; i++)
sum = sum + x[i];
av = (float)sum / SIZE;
printf(“The average of the numbers = %.2f\n”, av);
return 0;
}
Friday, September 8, 2023 4
Dr. Md. Abul Kashem Mia, Professor, CSE Dept, BUET
Sorting
Sorting an array is the ordering the array elements in
ascending (increasing: from min to max), or
descending (decreasing: from max to min) order.
Example:
{2, 1, 5, 3, 2} {1, 2, 2, 3, 5} ascending order
{2, 1, 5, 3, 2} {5, 3, 2, 2, 1} descending order
Underlined pairs show the comparisons. For each pass there are
size-1 comparisons.
Total number of comparisons = (size-1)2
Underlined pairs show the comparisons. For each pass there are
size-1 comparisons.
Total number of comparisons = (size-1)2
#include <stdio.h>
#define SIZE 5
void BubbleSort(int [ ]);
int main() {
int a[SIZE]= {2, 1, 5, 3, 2};
int i;
printf(“The elements of the array before sorting\n”);
for (i=0; i < SIZE; i++)
printf(“%4d”, a[i]);
BubbleSort(a);
printf(“\n\nThe elements of the array after sorting\n”);
for (i=0; i< SIZE; i++)
printf(“%4d”, a[i]);
return 0;
}
Friday, September 8, 2023 9
Dr. Md. Abul Kashem Mia, Professor, CSE Dept, BUET
Bubble Sort : C Code
void BubbleSort(int A[ ]) {
int i, pass, temp;
for (pass=1; pass < SIZE; pass++)
for (i=0; i < SIZE-1; i++)
if(A[i] > A[i+1]){
temp = A[i];
A[i] = A[i+1];
A[i+1] = temp;
}
}
Example:
Write a program to search for the search key entered by the
user in the following array:
(9, 4, 5, 1, 7, 78, 22, 15, 96, 45)
You can use the linear search in this example.
Example:
If a given sorted array 1024 elements, then the maximum number
of comparisons required is:
log2(1024) = 10 (only 10 comparisons is enough)
Example:
If a given an array of 1024 elements, then the maximum number of
comparisons required is:
n = 1024 (As many as 1024 comparisons may be required)