0% found this document useful (0 votes)
9 views32 pages

Daa Lab PDF

Uploaded by

Jayant Kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views32 pages

Daa Lab PDF

Uploaded by

Jayant Kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 32

[Approved by AICTE, Govt. of India & Affiliated to Dr.

APJ
Abdul Kalam Technical University, Lucknow, U.P., India]
Department of CSE - (AIML)

Lab File
Design and Analysis of Algorithm Lab (BCS-553)

Session: 2024-25

Submitted By:
Submitted To: Name: Jayant Kumar
Mr. Amit Kumar Himanshu Roll No.: 2201921530209
Branch: CSEAIML

Sec: CSAIML-4
Semester: V
[Approved by AICTE, Govt. of India & Affiliated to Dr. APJ
Abdul Kalam Technical University, Lucknow, U.P., India]
Department of CSE - (AIML)

INDEX
Date of Date of
S. No. List of Programs Signature
Experiment Submission
[Approved by AICTE, Govt. of India & Affiliated to Dr. APJ
Abdul Kalam Technical University, Lucknow, U.P., India]
Department of CSE - (AIML)

Program No -1
Aim: - Write a program to implement the Insertion Sort using array.

Insertion Sort:-
• Insertion sort is a simple sorting algorithm that works similar to the way you sort
playing cards in your hands. The array is virtually split into a sorted and an unsorted
part. Values from the unsorted part are picked and placed at the correct position in the
sorted part.
• Insertion Sort is a simple sorting algorithm that builds the final sorted array one item at
a time. It works by considering one element at a time and comparing it with the elements
to its left, shifting elements to the right as necessary to make room for the current
element.

Complexity:-
• Worst case complexity: O(n2)
• Best-case complexity: O(n)
• Average-case complexity: O(n2)

Algorithm:-
for j = 2 to A.length
key = A[j]
// Insert A[j] into the sorted sequence A[1.. j - 1]
i=j-1
while i > 0 and A[i] > key
A[i + 1] = A[i]
i = i -1
A[i + 1] = key

Process:

• We will store the random set of numbers in an array.


• We will traverse this array and insert each element of this array, to its correct position
where it should actually be, by shifting the other elements on the left if required.

The first element in the array is considered as sorted, even if it is an unsorted array.
The array is sub-divided into two parts, the first part holds the first element of the
array which is considered to be sorted and second part contains all the remaining
elements of array.
[Approved by AICTE, Govt. of India & Affiliated to Dr. APJ
Abdul Kalam Technical University, Lucknow, U.P., India]
Department of CSE - (AIML)

• With each iteration one element from the second part is picked and inserted into the
first part of array at its correct position by shifting the existing elements if required.

• This goes until the last element in second part of array is placed in correct position in
the output array.
• Now, we have the array in sorted order.
Source Code:-

#include<stdio.h>
int main() {
int n, temp, a[30];
printf("Enter the size of array\n");
scanf("%d",&n);
printf("Enter %d elements: \n",n);
for(int i=0; i<n; i++){
scanf("%d",&a[i]);
}
for(int i = 1; i <= n - 1; i++) {
for(int j = i; j > 0 && a[j - 1] > a[j]; j--) {
int temp = a[j];
a[j] = a[j - 1];
a[j - 1] = temp;
}
} printf("Sorted Array : ");
for(int i=0;i<n;i++){
printf("%d ",a[i]);
}
return 0;
}
[Approved by AICTE, Govt. of India & Affiliated to Dr. APJ
Abdul Kalam Technical University, Lucknow, U.P., India]
Department of CSE - (AIML)

Output:-
Enter the size of array
5
Enter 5 elements:
12 5 8 19 3
Sorted Array :
3 5 8 12 19
[Approved by AICTE, Govt. of India & Affiliated to Dr. APJ
Abdul Kalam Technical University, Lucknow, U.P., India]
Department of CSE - (AIML)

Program No -2

Aim: - Write a program to implement the Selection Sort using array.


Selection Sort: -

• Selection sort is a simple sorting algorithm. This sorting algorithm, like insertion sort, is
an in-place comparison-based algorithm in which the list is divided into two parts, the
sorted part at the left end and the unsorted part at the right end. Initially, the sorted part
is empty and the unsorted part is the entire list.
• The smallest element is selected from the unsorted array and swapped with the leftmost
element, and that element becomes a part of the sorted array. This process continues
moving unsorted array boundaries by one element to the right.

Complexity:-

• Worst case complexity: O(n2)


• Best-case complexity: O(n2)
• Average-case complexity: O(n2)

Algorithm:-

For i← 1 to n-1

do min j ←i;

min x ← A[i]

for j ←i + 1 to n

do if A[j] < min x

then

min j ← j

min x ← A[j]

A[min j] ← A [i]
A[i] ← min x
[Approved by AICTE, Govt. of India & Affiliated to Dr. APJ
Abdul Kalam Technical University, Lucknow, U.P., India]
Department of CSE - (AIML)

Process:

• Set the first element as minimum.


• Compare minimum with the second element. If the second element is smaller than
minimum, assign the second element as minimum. Compare minimum with the third
element. Again, if the third element is...
• After each iteration, minimum is placed in the front of the unsorted list.
• For each iteration, indexing starts from the first unsorted element. Step 1 to 3 are
repeated until all the elements are placed at their correct positions.

Source Code:-
#include<stdio.h>
int main() {
int n, i, j, temp, a[30], min;
printf("Enter the size of array : \n");
scanf("%d",&n);
printf("Enter %d elements : \n",n);
for(int i=0;i<n;i++){
scanf("%d",&a[i]);
} for (i = 0; i < n-1; i++) {
min = i;
for (j = i+1; j < n; j++) {
if (a[j] < a[min]) {
min = j;
}
} temp = a[min];
a[min] = a[i];
a[i] = temp;
} printf("Sorted Array : ");
for(int i=0;i<n;i++){
printf("%d ",a[i]);
[Approved by AICTE, Govt. of India & Affiliated to Dr. APJ
Abdul Kalam Technical University, Lucknow, U.P., India]
Department of CSE - (AIML)

}
return 0;
}
Output:-

Enter the size of array :


5
Enter 5 elements :
7 14 8 10 35
Sorted Array :
7 8 10 14 23
[Approved by AICTE, Govt. of India & Affiliated to Dr. APJ
Abdul Kalam Technical University, Lucknow, U.P., India]
Department of CSE - (AIML)

Program No -3

Aim : Write a program to implement the Bubble Sort using array.


Bubble Sort:
• Bubble Sort is a simple sorting algorithm that repeatedly steps through the list,
compares adjacent elements, and swaps them if they are in the wrong order. This
process continues until the entire list is sorted.
• The algorithm gets its name because elements "bubble" to their correct positions.
Complexity:
• Worst-case complexity: O(n²)
• Best-case complexity: O(n)
• Average-case complexity: O(n²)
Algorithm:
• Start: Begin at the first element of the array.
• Compare: Compare each pair of adjacent elements.
• Swap: If the current element is greater than the next element, swap them.
• Repeat: Continue comparing and swapping adjacent elements for all elements,
making several passes through the array.
• End: Repeat this process until the array is completely sorted.
Process:
• Traverse the array from the beginning to the end.
• In each traversal, compare adjacent elements and swap them if the current element is
greater than the next.
• After each full pass, the largest element will "bubble up" to the correct position at the
end of the array.
• Repeat this process until no more swaps are required, indicating that the array is
sorted.
[Approved by AICTE, Govt. of India & Affiliated to Dr. APJ
Abdul Kalam Technical University, Lucknow, U.P., India]
Department of CSE - (AIML)

Source Code:-

#include <stdio.h>
int main() {
int array[100], n, i, j, swap;
printf("Enter the size of array\n");
scanf("%d", &n);
printf("Enter %d integers\n", n);
for (i = 0; i < n; i++)
scanf("%d", &array[i]);
for (i = 0; i < n - 1; i++) {
for (j = 0; j < n - i - 1; j++) {
if (array[j] > array[j + 1]) {
swap = array[j];
array[j] = array[j + 1];
array[j + 1] = swap;
}
}
}
printf("Sorted array: ");
for (i = 0; i < n; i++)
printf("%d ", array[i]);
printf("\n");
return 0;
}

Output:-

Enter the size of array


5
Enter 5 integers
45 22 68 73 15
Sorted array:
15 22 45 68 73
[Approved by AICTE, Govt. of India & Affiliated to Dr. APJ
Abdul Kalam Technical University, Lucknow, U.P., India]
Department of CSE - (AIML)

Program No -4
Aim: - Write a program to implement the Binary Search using array.
Binary Search: -
• Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly
dividing the search interval in half.
• It is a search algorithm used to find the position of a target value within a sorted array.
It works by repeatedly dividing the search interval in half until the target value is
found or the interval is empty. The search interval is halved by comparing the target
element with the middle value of the search space.

Complexity:-

• Worst case complexity: O(logn)


• Best-case complexity: O(1)
• Average-case complexity: O(logn)

Algorithm:-

• Divide the search space into two halves by finding the middle index mid.
• Compare the middle element of the search space with the key.
• If the key is found at middle element, the process is terminated.
• If the key is not found at middle element, choose which half will be used as the next
search space.
• If the key is smaller than the middle element, then the left side is used for next search.
• If the key is larger than the middle element, then the right side is used for next search.
• This process is continued until the key is found or the total search space is exhausted.

Process:
• Start with two pointers, low at the beginning and high at the end of the array.
• Calculate the middle index: mid = (low + high) / 2.
Compare the target value with the middle element of the array.
• If the target value equals the middle element, the search is successful, and the index is
returned.
• If the target value is less than the middle element, adjust the high pointer to mid - 1 to
search the left half.
• If the target value is greater than the middle element, adjust the low pointer to mid + 1
to search the right half.
• Continue the process until the low pointer exceeds the high pointer or the target value
is found.
[Approved by AICTE, Govt. of India & Affiliated to Dr. APJ
Abdul Kalam Technical University, Lucknow, U.P., India]
Department of CSE - (AIML)

(a) Non-Recursive Approach


Source Code:-

#include <stdio.h>
int main() {
int n, i, x, beg, end, mid, flag=0;
int a[100];
printf("Enter the size of array: ");
scanf("%d", &n);
printf("Enter the array elements in sorted order:\n");
for (i = 0; i < n; i++) {
scanf("%d", &a[i]);
} printf("Enter the element to be searched: ");
scanf("%d", &x);
beg = 0;
end = n - 1;
while (beg <= end) {
mid = (beg + end) / 2;
if (a[mid] == x) {
printf("Element %d is found at index value %d\n", x, mid);
flag = 1;
break;
}
if (a[mid] > x) {
end = mid - 1;
} else {
beg = mid + 1;
}
} if (!flag) {
printf("No such element is found\n");
} return 0;
}
[Approved by AICTE, Govt. of India & Affiliated to Dr. APJ
Abdul Kalam Technical University, Lucknow, U.P., India]
Department of CSE - (AIML)

(b) Recursive Approach


Source Code:-

#include <stdio.h>
int binarySearch(int a[], int beg, int end, int x) {
if (beg > end) {
return -1;
} int mid = beg + (end - beg) / 2;
if (a[mid] == x) {
return mid;
} else if (a[mid] > x) {
return binarySearch(a, beg, mid - 1, x);
} else {
return binarySearch(a, mid + 1, end, x);
}
} int main() {
int n, i, x, result;
int a[100];
printf("Enter the size of array: ");
scanf("%d", &n);
printf("Enter the array elements in sorted order:\n");
for (i = 0; i < n; i++) {
scanf("%d", &a[i]);
}
printf("Enter the element to be searched: ");
scanf("%d", &x);
result = binarySearch(a, 0, n - 1, x);
if (result != -1) {
printf("Element %d is found at index value %d\n", x, result);
} else {
printf("No such element is found\n");
} return 0;
}
[Approved by AICTE, Govt. of India & Affiliated to Dr. APJ
Abdul Kalam Technical University, Lucknow, U.P., India]
Department of CSE - (AIML)

Output:-

Enter the size of array: 5


Enter the array elements in sorted order:
10 20 30 40 50
Enter the element to be searched: 40
Element 40 is found at index value 3
[Approved by AICTE, Govt. of India & Affiliated to Dr. APJ
Abdul Kalam Technical University, Lucknow, U.P., India]
Department of CSE - (AIML)

Program No -5

Aim: - Write a program to implement Merge Sort using array.


Merge Sort: -
- Merge Sort is a divide-and-conquer algorithm that splits the input array into two halves,
calls itself recursively on both halves, and then merges the two sorted halves.
- The merging step ensures that the final output is a sorted array.
Complexity:
- Worst-case complexity: O(n log n)
- Best-case complexity: O(n log n)
- Average-case complexity: O(n log n)
Algorithm:
- Divide: Split the array into two halves.
- Conquer: Recursively sort both halves.
- Combine: Merge the two sorted halves to get the final sorted array.

Process:
- Recursively divide the array until each subarray contains only one element.
- Merge the divided subarrays in a sorted manner.
- Continue merging until the entire array is sorted.

Source Code:

#include <stdio.h>

void merge(int array[], int left, int mid, int right) {


int i, j, k;
int n1 = mid - left + 1;
int n2 = right - mid;

int L[n1], R[n2];

for (i = 0; i < n1; i++)


L[i] = array[left + i];
for (j = 0; j < n2; j++)
R[j] = array[mid + 1 + j];
[Approved by AICTE, Govt. of India & Affiliated to Dr. APJ
Abdul Kalam Technical University, Lucknow, U.P., India]
Department of CSE - (AIML)

i = 0;
j = 0;
k = left;

while (i < n1 && j < n2) {


if (L[i] <= R[j]) {
array[k] = L[i];
i++;
} else {
array[k] = R[j];
j++;
}
k++;
}

while (i < n1) {


array[k] = L[i];
i++;
k++;
}

while (j < n2) {


array[k] = R[j];
j++;
k++;
}
}
void mergeSort(int array[], int left, int right) {

if (left < right) {


int mid = left + (right - left) / 2;

mergeSort(array, left, mid);


mergeSort(array, mid + 1, right);

merge(array, left, mid, right);


}
}
[Approved by AICTE, Govt. of India & Affiliated to Dr. APJ
Abdul Kalam Technical University, Lucknow, U.P., India]
Department of CSE - (AIML)

int main() {
int array[100], n, i;
printf("Enter number of elements: ");
scanf("%d", &n);
printf("Enter %d elements: ", n);
for (i = 0; i < n; i++)

scanf("%d", &array[i]);

mergeSort(array, 0, n - 1);

printf("Sorted array: ");


for (i = 0; i < n; i++)
printf("%d ", array[i]);

printf("\n");
return 0;
}

Output:

Enter number of elements: 5


Enter 5 elements: 38 27 43 3 9
Sorted array: 3 9 27 38 43
[Approved by AICTE, Govt. of India & Affiliated to Dr. APJ
Abdul Kalam Technical University, Lucknow, U.P., India]
Department of CSE - (AIML)

Program No -6

Aim: - Write a program to implement Heap Sort using array.

Heap Sort:
- Heap Sort is a comparison-based sorting algorithm that uses a binary heap data structure.
The algorithm builds a heap from the input data, then repeatedly extracts the maximum
element and rebuilds the heap until all elements are sorted.
- Heap: A complete binary tree where the value of each node is greater than or equal to the
values of its children (Max-Heap).

Complexity:
- Worst-case complexity: O(n log n)
- Best-case complexity: O(n log n)
- Average-case complexity: O(n log n)
Algorithm:
- Heapify: Build a max heap from the input data.
- Extract: Swap the root (maximum value) with the last element and reduce the heap size.
- Rebuild: Recursively heapify the root to maintain the heap property.
- Repeat: Continue until the heap size is reduced to 1.

Process:
- Build a max heap from the unsorted array.
- Swap the maximum element (root) with the last element in the array.
- Reduce the size of the heap and recursively heapify the remaining elements.
- Repeat the process until the entire array is sorted.

Source Code:

#include <stdio.h>

void heapify(int array[], int n, int i) {


int largest = i;
int left = 2 * i + 1;
int right = 2 * i + 2;

if (left < n && array[left] > array[largest])


[Approved by AICTE, Govt. of India & Affiliated to Dr. APJ
Abdul Kalam Technical University, Lucknow, U.P., India]
Department of CSE - (AIML)

largest = left;

if (right < n && array[right] > array[largest])


largest = right;

if (largest != i) {
int temp = array[i];
array[i] = array[largest];
array[largest] = temp;
heapify(array, n, largest);

}
}

void heapSort(int array[], int n) {


for (int i = n / 2 - 1; i >= 0; i--)
heapify(array, n, i);

for (int i = n - 1; i >= 0; i--) {


int temp = array[0];
array[0] = array[i];
array[i] = temp;

heapify(array, i, 0);
}
}

int main() {
int array[100], n, i;

printf("Enter number of elements: ");


scanf("%d", &n);
printf("Enter %d elements: ", n);
for (i = 0; i < n; i++)
scanf("%d", &array[i]);

heapSort(array, n);
[Approved by AICTE, Govt. of India & Affiliated to Dr. APJ
Abdul Kalam Technical University, Lucknow, U.P., India]
Department of CSE - (AIML)

printf("Sorted array: ");


for (i = 0; i < n; i++)
printf("%d ", array[i]);

printf("\n");
return 0;
}

Output:

Enter number of elements: 5


Enter 5 elements: 12 11 13 5 6
Sorted array: 5 6 11 12 13
[Approved by AICTE, Govt. of India & Affiliated to Dr. APJ
Abdul Kalam Technical University, Lucknow, U.P., India]
Department of CSE - (AIML)

Program No -7
Aim:- Write a program to count the number of Inversions in an array using the Merge
algorithm.

Inversion:
• The merge algorithm is a key component of the merge sort technique, which
efficiently sorts arrays.
• An inversion is a condition in which a pair of elements is out of order. Specifically,
for an array AAA, a pair (i,j)(i, j)(i,j) forms an inversion if i<ji < ji<j and
A[i]>A[j]A[i] > A[j]A[i]>A[j].
• By counting inversions during the merging of two sorted subarrays, we can determine
how out of order the array is.

Complexity:
- Worst-case complexity: O(n log n)
- Best-case complexity: O(n log n)
- Average-case complexity: O(n log n)

Algorithm:
- Start by dividing the array into two sorted subarrays.
- Merge the two sorted subarrays while counting the inversions:
• Compare elements of both subarrays.
• If an element in the left subarray is greater than an element in the right subarray, count
how many elements are left in the left subarray (as they are all inversions).
- Continue until all elements are merged and counted.

Process:
- Take two sorted subarrays.
- Use the merge function to combine them and count the inversions.
- Display the total count of inversions and the final merged array..
[Approved by AICTE, Govt. of India & Affiliated to Dr. APJ
Abdul Kalam Technical University, Lucknow, U.P., India]
Department of CSE - (AIML)

Source Code:

#include <stdio.h>
int countInversions(int left[], int right[], int n1, int n2, int merged[]) {
int i = 0, j = 0, k = 0;
int inversion_count = 0;
while (i < n1 && j < n2) {
if (left[i] <= right[j]) {
merged[k++] = left[i++];
} else {
merged[k++] = right[j++];
inversion_count += (n1 - i);
}
}
while (i < n1)
merged[k++] = left[i++];
while (j < n2)
merged[k++] = right[j++];
return inversion_count;
}
int main() {
int left[] = {10, 50, 60, 70};
int right[] = {15, 20, 30, 80};
int n1 = sizeof(left) / sizeof(left[0]);
int n2 = sizeof(right) / sizeof(right[0]);
int merged[n1 + n2];
int inversion_count = countInversions(left, right, n1, n2, merged);
printf("Number of inversions: %d\n", inversion_count);
printf("Merged array: ");
for (int i = 0; i < n1 + n2; i++) {
printf("%d ", merged[i]);
}
printf("\n");

return 0;
}
Output:
Number of inversions: 6
Merged array: 10 15 20 30 50 60 70 80
[Approved by AICTE, Govt. of India & Affiliated to Dr. APJ
Abdul Kalam Technical University, Lucknow, U.P., India]
Department of CSE - (AIML)

Program No -8

Aim : Write a program to implement Quick Sort using an array.


Quick Sort:
- Quick Sort is a divide-and-conquer algorithm that selects a "pivot" element and partitions
the array around the pivot. The process is recursively applied to the sub-arrays.

Complexity:
- Worst-case complexity: O(n²)
- Best-case complexity: O(n log n)
- Average-case complexity: O(n log n)

Algorithm:
- Start: Select a pivot element from the array.
- Partition: Rearrange elements so that all elements less than the pivot come before it, and all
elements greater come after it.
- Recursion: Recursively apply the same process to the sub-arrays formed by partitioning.
- End: Repeat until the array is fully sorted.

Process:
1. Select a pivot element (usually the last element).
2. Rearrange elements around the pivot such that elements smaller than the pivot are to the
left and larger elements to the right.
3. Recursively apply the steps to the left and right partitions until the base case (sub-arrays of
size 1 or 0) is reached.
Source Code:

#include <stdio.h>

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


int t = *a;
*a = *b;
*b = t;
}

int partition(int array[], int low, int high) {


[Approved by AICTE, Govt. of India & Affiliated to Dr. APJ
Abdul Kalam Technical University, Lucknow, U.P., India]
Department of CSE - (AIML)

int pivot = array[high];


int i = (low - 1);
for (int j = low; j < high; j++) {
if (array[j] < pivot) {
i++;
swap(&array[i], &array[j]);
}
}
swap(&array[i + 1], &array[high]);
return (i + 1);
}

void quickSort(int array[], int low, int high) {


if (low < high) {
int pi = partition(array, low, high);
quickSort(array, low, pi - 1);
quickSort(array, pi + 1, high);
}
}

int main() {
int data[] = {8, 7, 6, 1, 0, 9, 2};
int n = sizeof(data) / sizeof(data[0]);

quickSort(data, 0, n - 1);

printf("Sorted array: \n");


for (int i = 0; i < n; i++)
printf("%d ", data[i]);
printf("\n");
return 0;
}

Output:

Sorted array:
0126789
[Approved by AICTE, Govt. of India & Affiliated to Dr. APJ
Abdul Kalam Technical University, Lucknow, U.P., India]
Department of CSE - (AIML)

Program No -9

Aim: Write a program to implement Shell Sort using an array.

Shell Sort:
- Shell Sort is a generalization of insertion sort that allows the exchange of far-apart elements
to speed up the sorting process. It works by repeatedly sorting elements that are a certain
distance apart (gap), gradually reducing the gap.

Complexity:
- Worst-case complexity: O(n²)
- Best-case complexity: O(n log n)
- Average-case complexity: O(n log² n)
Algorithm:
- Start: Divide the list into smaller sub-lists.
- Gap: Select a gap value and sort sub-lists formed by the gap.
- Insertion Sort: Apply the insertion sort algorithm to the sub-lists.
- Repeat: Reduce the gap size and repeat the process.
- End: The process ends when the gap is reduced to 1, effectively performing an insertion
sort.

Process:
1. Choose an initial gap (typically n/2).
2. Apply insertion sort for elements at that gap distance.
3. Reduce the gap and repeat until the gap becomes 1.

Source Code:

#include <stdio.h>
void shellSort(int arr[], int n) {
for (int gap = n / 2; gap > 0; gap /= 2) {
for (int i = gap; i < n; i++) {
int temp = arr[i];
int j;
for (j = i; j >= gap && arr[j - gap] > temp; j -= gap)
arr[j] = arr[j - gap];
arr[j] = temp;
}}}
int main() {
[Approved by AICTE, Govt. of India & Affiliated to Dr. APJ
Abdul Kalam Technical University, Lucknow, U.P., India]
Department of CSE - (AIML)

int arr[] = {12, 34, 54, 2, 3};


int n = sizeof(arr) / sizeof(arr[0]);
shellSort(arr, n);

printf("Sorted array: \n");


for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");
return 0;
}

Output:

Sorted array: 2 3 12 34 54
[Approved by AICTE, Govt. of India & Affiliated to Dr. APJ
Abdul Kalam Technical University, Lucknow, U.P., India]
Department of CSE - (AIML)

Program No -10

Aim: Write a program to implement Counting Sort using an array.


Counting Sort:
- Counting Sort is a non-comparative sorting algorithm that works by counting the frequency
of each element and then using this count to place elements in their correct positions.

Complexity:
- Worst-case complexity: O(n + k)
- Best-case complexity: O(n + k)
- Average-case complexity: O(n + k)

Algorithm:
- Start: Count the occurrences of each element.
- Accumulate: Modify the count array to accumulate the counts.
- Place: Place each element in its correct sorted position based on the counts.
- End: Output the sorted array.

Process:
1. Count the occurrences of each element.
2. Update the count array by adding the previous counts.
3. Place the elements in their correct positions.

Source Code:

#include <stdio.h>

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


int output[10];
int count[10];
int max = array[0];

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


if (array[i] > max)
max = array[i];
}

for (int i = 0; i <= max; i++)


count[i] = 0;
[Approved by AICTE, Govt. of India & Affiliated to Dr. APJ
Abdul Kalam Technical University, Lucknow, U.P., India]
Department of CSE - (AIML)

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


count[array[i]]++;

for (int i = 1; i <= max; i++)


count[i] += count[i - 1];

for (int i = size - 1; i >= 0; i--) {


output[count[array[i]] - 1] = array[i];
count[array[i]]--;
}

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


array[i] = output[i];
}

int main() {
int array[] = {4, 2, 2, 8, 3, 3, 1};
int size = sizeof(array) / sizeof(array[0]);

countingSort(array, size);

printf("Sorted array: \n");


for (int i = 0; i < size; i++)
printf("%d ", array[i]);
printf("\n");
return 0;
}

Output:

Sorted array: 1 2 2 3 3 4 8
[Approved by AICTE, Govt. of India & Affiliated to Dr. APJ
Abdul Kalam Technical University, Lucknow, U.P., India]
Department of CSE - (AIML)

Program No -11

Aim: Write a program to implement Radix Sort using an array.

Radix Sort:
- Radix Sort sorts elements by processing individual digits of each number, starting from the
least significant bit (LSB) to the most significant bit (MSB).

Complexity:
- Worst-case complexity: O(nk) (where k is the number of digits in the largest number)
- Best-case complexity: O(nk)
- Average-case complexity: O(nk)

Algorithm:
- Start: Group the numbers by their least significant digit.
- Sort: Sort each group, and repeat the process for each more significant digit.
- Repeat: Continue until all digits have been processed.
- End: The array is sorted.

Process:
1. Perform a stable sort for each digit.
2. Process from the least significant to the most significant digit.

Source Code:

#include <stdio.h>

int getMax(int arr[], int n) {


int max = arr[0];
for (int i = 1; i < n; i++)
if (arr[i] > max)
max = arr[i];
return max;
}

void countingSort(int arr[], int n, int exp) {


[Approved by AICTE, Govt. of India & Affiliated to Dr. APJ
Abdul Kalam Technical University, Lucknow, U.P., India]
Department of CSE - (AIML)

int output[n];
int count[10] = {0};
for (int i = 0; i < n; i++)
count[(arr[i] / exp) % 10]++;

for (int i = 1; i < 10; i++)


count[i] += count[i - 1];

for (int i = n - 1; i >= 0; i--) {


output[count[(arr[i] / exp) % 10] - 1] = arr[i];
count[(arr[i] / exp) % 10]--;
}
for (int i = 0; i < n; i++)

arr[i] = output[i];
}

void radixSort(int arr[], int n) {


int m = getMax(arr, n);
for (int exp = 1; m / exp > 0; exp *= 10)
countingSort(arr, n, exp);
}

int main() {
int arr[] = {170, 45, 75, 90, 802, 24, 2, 66};
int n = sizeof(arr) / sizeof(arr[0]);
radixSort(arr, n);
printf("Sorted array: \n");
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");
return 0;
}

Output:

Sorted array: 2 24 45 66 75 90 170 802


[Approved by AICTE, Govt. of India & Affiliated to Dr. APJ
Abdul Kalam Technical University, Lucknow, U.P., India]
Department of CSE - (AIML)

Program No -12
Aim: Write a program to implement Bucket Sort using an array.

Bucket Sort:
- Bucket Sort divides elements into buckets, sorts each bucket individually, and then merges
the buckets to get the sorted array.

Complexity:
- Worst-case complexity: O(n²)
- Best-case complexity: O(n + k)
- Average-case complexity: O(n + k)

Algorithm:
- Start: Divide the array into buckets.
- Sort: Sort each bucket using another sorting algorithm (usually Insertion Sort).
- Merge: Merge the sorted buckets into a single sorted array.
- End: The array is sorted.

Process:
1. Create buckets and distribute the elements.
2. Sort each bucket.
3. Combine the sorted buckets into the final sorted array.

Source Code:

#include <stdio.h>
#include <stdlib.h>
#define NBUCKET 10
#define INTERVAL 10
struct Node {
int data;
struct Node *next;

};

void bucketSort(int arr[], int n) {


int i, j;
struct Node **buckets;
[Approved by AICTE, Govt. of India & Affiliated to Dr. APJ
Abdul Kalam Technical University, Lucknow, U.P., India]
Department of CSE - (AIML)

buckets = (struct Node **)malloc(sizeof(struct Node *) * NBUCKET);

for (i = 0; i < NBUCKET; i++)


buckets[i] = NULL;
for (i = 0; i < n; i++) {

int idx = arr[i] / INTERVAL;


struct Node *newNode = (struct Node *)malloc(sizeof(struct Node));
newNode->data = arr[i];
newNode->next = buckets[idx];
buckets[idx] = newNode;
}

for (i = 0; i < NBUCKET; i++) {


struct Node *node = buckets[i];
while (node != NULL) {
arr[j++] = node->data;
node = node->next;
}
}
free(buckets);
}

int main() {
int array[] = {29, 25, 3, 49, 9, 37, 21, 43};
int n = sizeof(array) / sizeof(array[0]);

bucketSort(array, n);

printf("Sorted array: \n");


for (int i = 0; i < n; i++)
printf("%d ", array[i]);
printf("\n");
return 0;
}

Output:

Sorted array: 3 9 21 25 29 37 43 49

You might also like