DSA 2
DSA 2
DSA 2
Set A
a) Sort a random array of n integers (accept the value of n from user) in ascending order
by using bubble sort algorithm.
#include <stdio.h>
#include<conio.h>
int i, j, temp;
temp = array[j];
array[j + 1] = temp;
int main()
int n, i;
scanf("%d", &n);
int array[10];
scanf("%d", &array[i]);
}
printf("Array before sorting:\n");
bubbleSort(array, n);
Getch();
Clrscr();
return 0;
}
b) Sort a random array of n integers (create a random array of n integers) in ascending order by using
insertion sort algorithm.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int i, key, j;
key = arr[i];
j = i - 1;
arr[j + 1] = arr[j];
j = j - 1;
arr[j + 1] = key;
int main()
int n;
scanf("%d", &n);
int arr[n];
srand(time(0));
printf("\n");
insertionSort(arr, n);
printf("\n");
return 0;
}
c) Sort a random array of n integers (accept the value of n from user) in ascending order
by using selection sort algorithm.
#include <stdio.h>
#include<conio.h>
min_idx = i;
min_idx = j;
temp = array[min_idx];
array[min_idx] = array[i];
array[i] = temp;
int main()
int n, i;
scanf("%d", &n);
int array[10];
scanf("%d", &array[i]);
selectionSort(array, n);
getch();
clrscr();
return 0;
}
Set B
a) Read the data from the file “employee.txt” and sort on age using bubble sort,
insertion sort and selection sort.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Employee
char name[50];
int age;
};
if (file == NULL)
return -1;
int i = 0;
while (fscanf(file, "%s %d", employees[i].name, &employees[i].age)!= EOF && i < max_size)
i++;
fclose(file);
return i;
printf("Name - Age");
}
void bubbleSort(struct Employee employees[], int n)
temp = employees[j];
employees[j] = employees[j+1];
employees[j+1] = temp;
int j = i - 1;
employees[j + 1] = employees[j];
j--;
employees[j + 1] = key;
int min_index = i;
for (int j = i+1; j < n; j++)
min_index = j;
employees[i] = employees[min_index];
employees[min_index] = temp;
int main()
if (n == -1)
return 1;
printEmployees(employees, n);
bubbleSort(employees, n);
printEmployees(employees, n);
insertionSort(employees, n);
printEmployees(employees, n);
selectionSort(employees, n);
printEmployees(employees, n);
return 0;
}
Set C
a) What modification is required to bubble sort, insertion sort and selection to sort the integers in descending
order?
#include <stdio.h>
arr[j + 1] = temp;
int j = i - 1;
arr[j + 1] = arr[j];
j--;
arr[j + 1] = key;
int maxIndex = i;
maxIndex = j;
if (maxIndex != i) {
int temp = arr[i];
arr[i] = arr[maxIndex];
arr[maxIndex] = temp;
printf("\n");
int main() {
printf("Original array:\n");
bubbleSortDescending(arr, size);
printArray(arr, size);
insertionSortDescending(arr2, size);
printArray(arr2, size);
selectionSortDescending(arr3, size);
printArray(arr3, size);
return 0;