0% found this document useful (0 votes)
29 views15 pages

202411005_ CS162_4

The document outlines the course details for a Data Structures Lab, including student and faculty information, and an assessment on sorting algorithms. It provides specific programming tasks for implementing various sorting algorithms such as Insertion Sort, Bubble Sort, Selection Sort, Merge Sort, and Quick Sort, along with sample code and output observations. The document emphasizes the importance of documenting the sorting process, comparisons, and performance analysis for each algorithm.

Uploaded by

krishajudiya21
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)
29 views15 pages

202411005_ CS162_4

The document outlines the course details for a Data Structures Lab, including student and faculty information, and an assessment on sorting algorithms. It provides specific programming tasks for implementing various sorting algorithms such as Insertion Sort, Bubble Sort, Selection Sort, Merge Sort, and Quick Sort, along with sample code and output observations. The document emphasizes the importance of documenting the sorting process, comparisons, and performance analysis for each algorithm.

Uploaded by

krishajudiya21
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/ 15

Semester Course Code Course Title

Data Structures Lab


Winter 2024-25 CS162

Student Details: Student Name: Krish Prafulkumar Ajudiya


Roll/Reg No: 202411005
Email: [email protected]
Mobile: 8799400820
Faculty Details: Faculty Name: Dr. VENKATA PHANIKRISHNA B
Department: Computer Science and Engineering
Email: [email protected]
Assessment No: 4
Assessment Title. Implementation of Sorting Algorithms Part 1 (Comparison based
sorting)

Date of Submission 7-Mar-2025

Format/Frame Work
Question Provided by the professor.
Program Must be typed content (not screenshots).
Can include program code, syntax, or relevant theory.
Include your roll number and name in comments.
Output: Typed or copy-pasted content of your program's output is preferred.
If difficult, output screenshots are acceptable.
Note: Ensure your name is included in the comments of all submitted programs.
Your
Observation

A4: Implementation of Sorting Algorithms Part 1(Comparison based sorting)

 A4: P1@Write a program to implement Insertion Sort.


 A4: P2@Write a program to implement Bubble Sort.
 A4: P3@Write a program to implement Selection Sort.
 A4: P4@Write a program to implement Merge Sort.
 A4: P5@Write a program to implement Quick Sort.
 A4: P6@Write a program to implement Heap Sort.
Question 1  A4: P1@Write a program to implement Insertion Sort.

Program #include <stdio.h>

int main() {
int n;
scanf("%d", &n);
int arr[n];
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
printf("Sorting process:\n\n");
int comp = 0;
int shift = 0;

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


int j = i;
printf("Pass %d (i=%d, key=%d):\n", i, i, arr[i]);
int c = 0; // Flag to track if shifts occurred in this pass
while (j > 0 && arr[j] < arr[j-1]) {
printf("Comparing %d and %d -> Shifted %d to right\n", arr[j], arr[j-1], arr[j-1]);
// XOR swap
arr[j] = arr[j] ^ arr[j-1];
arr[j-1] = arr[j] ^ arr[j-1];
arr[j] = arr[j] ^ arr[j-1];
j--;
shift++;
comp++; // Count each shift as a comparison
c = 1;
}
if (c == 1) {
comp++; // Add one comparison for the final check that stopped the loop
printf("Insert %d at index %d -> [", arr[j], j);
for (int k = 0; k < n; k++) {
printf("%d", arr[k]);
if (k < n - 1) printf(", ");
}
printf("].\n");
} else {
printf("No shifts needed, %d remains at position %d -> [", arr[i], i);
for (int k = 0; k < n; k++) {
printf("%d", arr[k]);
if (k < n - 1) printf(", ");
}
printf("].\n");
}
printf("\n");
}
printf("Final Sorted array: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
printf("Total Comparisons: %d\n", comp);
printf("Total Shifts: %d\n", shift);

if (shift == 0) {
printf("Best Case: O(n) - Already Sorted Input.\n");
} else if (shift == (n * (n - 1)) / 2) {
printf("Worst Case: O(n^2) - Reverse Sorted Input.\n");
} else {
printf("Average Case: O(n^2) - Random Order Input.\n");
}
printf("\n");
return 0;
}
Output:

Your This code teaches Insertion Sort, showing how it compares and shifts elements to sort an
Observation array, with explanations for best, worst, and average cases

Question 2  A4: P2@Write a program to implement Bubble Sort.

Program #include <stdio.h>

int main() {
int n, swap = 0, com = 0;
scanf("%d", &n);
int arr[n];

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


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

printf("Sorting process:\n\n");
for(int i = 0; i < n - 1; i++){
int swapped = 0;
printf("Pass %d:\n", i + 1);
for(int j = 0; j < n - i - 1; j++) {
printf("Comparing %d and %d -> ", arr[j], arr[j + 1]);
if(arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
printf("Swapped to get: ");
for(int k = 0; k < n; k++) printf("%d ", arr[k]);
printf("\n");
swap++;
swapped = 1;
} else {
printf("No Swap, so Same previous View: ");
for(int k = 0; k < n; k++) printf("%d ", arr[k]);
printf("\n");
}
com++;
}
if(!swapped) break;
printf("\n");
}

printf("Sorted array: ");


for(int i = 0; i < n; i++) printf("%d ", arr[i]);
printf("\n");
printf("Total Comparisons: %d\n", com);
printf("Total Swaps: %d\n", swap);

int sum = n * (n - 1) / 2;

if(swap == 0) {
printf("Best Case: O(n) - Already Sorted Input.\n");
} else if(swap == sum) {
printf("Worst Case: O(n^2) - Reverse Sorted Input.\n");
} else {
printf("Average Case: O(n^2) - Random Order Input.\n");
}

return 0;
}
Output:

Your This code demonstrates Bubble Sort, showing how it compares and swaps adjacent
Observation elements to sort an array, with explanations for best, worst, and average cases.

Question 3  A4: P3@Write a program to implement Selection Sort.

Program #include <stdio.h>

int main()
{
int n;
scanf("%d",&n);
int arr[n];
for(int i=0;i<n;i++){
scanf("%d",&arr[i]);
}

int c = 0;
int s = 0;

printf("Sorting process:\n");
for(int i=0;i<n-1;i++){
printf("Pass %d (i=%d):\n", i+1, i);
printf("Unsorted: [");
for(int k=i; k<n; k++) {
printf("%d", arr[k]);
if(k < n-1) printf(" ");
}
printf("]\n");

int min=i;
for(int j=i+1;j<n;j++){
c++;
int m = arr[min];
if(arr[j]<arr[min]) {
printf("Comparing %d and %d ==> Now Min %d\n", m, arr[j], arr[j]);
min=j;
}
else {
printf("Comparing %d and %d ==> Now Min %d\n", m, arr[j], m);
}
}
printf("Final Minimum: %d (index %d).\n", arr[min], min);

if(min != i) {
int x = arr[i];
int y = arr[min];
arr[i]=arr[i]^arr[min];
arr[min]=arr[i]^arr[min];
arr[i]=arr[i]^arr[min];
s++;
printf("Swapped %d (index %d) and %d (index %d) -> [", x, i, y, min);
for(int k=0; k<n; k++) {
printf("%d", arr[k]);
if(k < n-1) printf(" ");
}
printf("]\n");
}
else {
printf("No Swap needed, %d remains at position %d-> [", arr[i], i);
for(int k=0; k<n; k++) {
printf("%d", arr[k]);
if(k < n-1) printf(" ");
}
printf("]\n");
}
}
printf("Pass %d (i=%d):\n", n, n-1);
printf("Only one element left. Sorting complete.\n");

printf("Final Sorted array: [");


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

printf("Total Comparisons: %d\n", c);


printf("Total Swaps: %d\n", s);

return 0;
}
Output:

Your This code explains selection sort, where it finds the smallest element in each pass and
Observation swaps it to the right position. It shows the sorting process step-by-step, including
comparisons and swaps, and counts the total comparisons and swaps made.

Question 4 A4: P4@Write a program to implement Merge Sort

Program #include <stdio.h>


#include <stdlib.h>

int temp[100];
int total_splits = 0;
int total_comparisons = 0;
int total_swaps = 0;

void print_subarray(int arr[], int start, int end) {


printf("[");
for (int i = start; i <= end; i++) {
printf("%d", arr[i]);
if (i < end) printf(" ");
}
printf("]");
}

void mergeing_array(int arr[], int l, int mid, int h) {


printf("Merging (Indices: left=%d, mid=%d, right=%d):\n", l, mid, h);
printf("Left=");
print_subarray(arr, l, mid);
printf(", Right=");
print_subarray(arr, mid + 1, h);
printf("\n");

int left = l;
int right = mid + 1;
int i = 0;

while (left <= mid && right <= h) {


total_comparisons++;
if (arr[left] <= arr[right]) {
printf("Compare %d with %d, place %d.\n", arr[left], arr[right], arr[left]);
temp[i++] = arr[left++];
} else {
printf("Compare %d with %d, place %d.\n", arr[left], arr[right], arr[right]);
temp[i++] = arr[right++];
}
total_swaps++;
}

while (left <= mid) {


printf("Place the remaining %d.\n", arr[left]);
temp[i++] = arr[left++];
total_swaps++;
}

while (right <= h) {


printf("Place the remaining %d.\n", arr[right]);
temp[i++] = arr[right++];
total_swaps++;
}

for (int j = l; j <= h; j++) {


arr[j] = temp[j - l];
}

printf("After Merge: ");


print_subarray(arr, l, h);
printf("\n");
}

void ms(int arr[], int l, int h) {


if (l == h) return;
int mid = (l + h) / 2;
total_splits++;
printf("Splitting (Indices: left=%d, mid=%d, right=%d):\n", l, mid, h);
print_subarray(arr, l, h);
printf(" -> Left=");
print_subarray(arr, l, mid);
printf(", Right=");
print_subarray(arr, mid + 1, h);
printf("\n");

ms(arr, l, mid);
ms(arr, mid + 1, h);
mergeing_array(arr, l, mid, h);
}

int main() {
printf("Starting Merge Sort...\n");
int n;
scanf("%d",&n);
int arr[n];
for(int i=0;i<n;i++){
scanf("%d",&arr[i]);
}

int is_sorted = 1;
int is_reverse_sorted = 1;
for (int i = 0; i < n - 1; i++) {
if (arr[i] > arr[i+1]) is_sorted = 0;
if (arr[i] < arr[i+1]) is_reverse_sorted = 0;
}

ms(arr, 0, n - 1);

printf("Sorted Array: ");


print_subarray(arr, 0, n - 1);
printf("\n");

printf("\nPerformance Analysis:\n");
printf("Total Splits: %d\n", total_splits);
printf("Total Comparisons: %d\n", total_comparisons);
printf("Total Swaps: %d\n", total_swaps);
if (is_sorted) {
printf("Input Type: Best Case\n");
} else if (is_reverse_sorted) {
printf("Input Type: Worst Case\n");
} else {
printf("Input Type: Average Case\n");
}

printf("\nTime Complexity Analysis:\n");


printf("Best Case (Already Sorted) : O(n log n)\n");
printf("Worst Case (Reversed Order) : O(n log n)\n");
printf("Average Case : O(n log n)\n");

return 0;
}
Output:

Your This code demonstrates merge sort, showing how it splits the array into smaller parts,
Observation merges them in sorted order, and counts splits, comparisons, and swaps. It also analyzes
the time complexity for best, worst, and average cases.

Question 5  A4: P5@Write a program to implement Quick Sort.

Program #include <stdio.h>

int size;
int splits = 0;
int comparisons = 0;
int swaps = 0;

int find_pivot(int arr[], int l, int h) {


int pivot = arr[h];
printf("Pivot: %d\n", pivot);
int i = l - 1;
for (int j = l; j < h; j++) {
printf("Pivot Index=%d, j=%d, Comparing: arr[%d]=%d and pivot=%d, Updated
Array: ", i, j, j, arr[j], pivot);
for (int k = 0; k < size; k++) printf("%d ", arr[k]);
printf("\n");
comparisons++;
if (arr[j] <= pivot) {
i++;
if (i != j) {
printf("Updated Pivot Index=%d Swapped: arr[%d]=%d and arr[%d]=%d,
Updated Array: ", i, i, arr[i], j, arr[j]);
arr[i] = arr[i] ^ arr[j];
arr[j] = arr[i] ^ arr[j];
arr[i] = arr[i] ^ arr[j];
swaps++;
for (int k = 0; k < size; k++) printf("%d ", arr[k]);
printf("\n");
} else {
printf("No swap needed, already in place: arr[%d]=%d, Updated Array: ", j,
arr[j]);
for (int k = 0; k < size; k++) printf("%d ", arr[k]);
printf("\n");
}
}
}
i++;
int temp = arr[i];
printf("Comparing all elements in array with Pivot is completed, Updated Pivot
Index=%d, Swapped: pivot %d and arr[%d]=%d\n", i, pivot, i, temp);
if (i != h) {
arr[i] = arr[i] ^ arr[h];
arr[h] = arr[i] ^ arr[h];
arr[i] = arr[i] ^ arr[h];
swaps++;
}
printf("NowPlaced pivot %d at correct position\n", pivot);
printf("Partitioned Array: ");
for (int k = 0; k < size; k++) printf("%d ", arr[k]);
printf("\n");
return i;
}

void qs(int arr[], int l, int h) {


static int depth = 0;
if (l < h) {
depth++;
splits++;
printf("\nRecursion depth %d: QuickSort(%d, %d)\n", depth, l, h);
int x = find_pivot(arr, l, h);
qs(arr, l, x - 1);
qs(arr, x + 1, h);
depth--;
}
}

int main() {
scanf("%d", &size);
int arr[size];
for (int i = 0; i < size; i++) scanf("%d", &arr[i]);
printf("Initial Array: ");
for (int i = 0; i < size; i++) printf("%d ", arr[i]);
printf("\n\nSorting Steps:\n");
qs(arr, 0, size - 1);
printf("\nSorted Array: ");
for (int i = 0; i < size; i++) printf("%d ", arr[i]);
printf("\n\nPerformance Analysis:\n");
printf("Total Splits: %d\n", splits);
printf("Total Comparisons: %d\n", comparisons);
printf("Total Swaps: %d\n", swaps);
if (splits == size - 1) printf("Case: Worst Case (O(n^2))\n");
else printf("Case: Best Case (O(n log n))\n");
return 0;
}
Output:

Your This code demonstrates quick sort, showing how it selects a pivot, partitions the array, and
Observation recursively sorts the subarrays. It counts splits, comparisons, and swaps, and analyzes the
time complexity for best and worst cases.

Question 6 A4: P6@Write a program to implement Heap Sort.

Program #include <stdio.h>

int comps = 0;
int swaps = 0;

void print_array(int *arr, int size, int h1, int h2) {


for (int i = 0; i < size; i++) {
if (i == h1 || i == h2) {
printf("[%d]", arr[i]);
} else {
printf("%d", arr[i]);
}
if (i < size - 1) printf(" ");
}
printf("\n");
}

void heapify(int *arr, int n, int i) {


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

if (left < n) {
printf(" Comparing %d (index %d) with left child %d (index %d)\n", arr[large], large,
arr[left], left);
comps++;
if (arr[left] > arr[large]) {
large = left;
}
}

if (right < n) {
printf(" Comparing %d (index %d) with right child %d (index %d)\n", arr[large],
large, arr[right], right);
comps++;
if (arr[right] > arr[large]) {
large = right;
}
}

if (large != i) {
printf(" !! SWAPPING %d (index %d) with %d (index %d)\n", arr[i], i, arr[large],
large);
int temp = arr[large];
arr[large] = arr[i];
arr[i] = temp;
swaps++;
printf(" Array state: ");
print_array(arr, n, i, large);
heapify(arr, n, large);
}
}

void heapsort(int *arr, int n) {


printf("\nBuilding Max Heap:\n\n");
for (int i = n / 2 - 1; i >= 0; i--) {
printf("Heapifying subtree rooted at index %d (%d):\n", i, arr[i]);
heapify(arr, n, i);
printf("Subtree after heapify: ");
print_array(arr, n, i, -1);
if (i > 0) printf("\n\n");
}

printf("\nSorting Phase:\n\n");
for (int i = n - 1; i > 0; i--) {
printf("=== Moving root %d (index 0) to final position %d ===\n", arr[0], i);
printf(" Before swap: ");
print_array(arr, i + 1, 0, i);
int temp = arr[0];
arr[0] = arr[i];
arr[i] = temp;
swaps++;
printf(" After swap: ");
print_array(arr, n, 0, i);
printf("Heapifying new root:");
heapify(arr, i, 0);
if (i > 1) printf("\n");
}
}

int main() {
int n;
scanf("%d", &n);
int arr[n];
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
printf("Initial array: ");
print_array(arr, n, -1, -1);
printf("\n");
heapsort(arr, n);
printf("\nFinal sorted array: ");
print_array(arr, n, -1, -1);
printf("Total comparisons: %d\n", comps);
printf("Total swaps: %d\n", swaps);
return 0;
}
Output:

Your This code demonstrates heap sort, showing how it builds a max heap, swaps the root with
Observation the last element, and heapifies the remaining array. It counts comparisons and swaps, and
visualizes the sorting process step-by-step.

You might also like