sDSA-LAB04
sDSA-LAB04
LAB # 04
Lab Tasks
1. Create a program that take an array of 10 inputs from the user and generate the
sorted out put using the following Algorithm:
Bubble Sort
Code :
#include <iostream>
using namespace std;
void bubbleSort(int arr[], int size) {
for (int i = 0; i < size - 1; i++) {
for (int j = 0; j < size - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
int main() {
cout << "Hira Fatima" << endl;
cout << "2023F-BIT-027" << endl;
cout << "\n" << endl;
const int SIZE = 10;
int arr[SIZE];
cout << "Enter 10 integers: ";
for (int i = 0; i < SIZE; i++) {
cin >> arr[i];
}
bubbleSort(arr, SIZE);
cout << "Sorted array in ascending order: ";
for (int i = 0; i < SIZE; i++) {
cout << arr[i] << " ";
}
cout << endl;
return 0;
}
Output :
2. Create a program that take an array of 10 inputs from the user and generate the sorted
out put using the following Algorithm:
Selection Sort
Code :
#include <iostream>
using namespace std;
void selectionSort(int arr[], int n) {
for (int i = 0; i < n - 1; i++) {
int minIndex = i;
for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
swap(arr[i], arr[minIndex]);
}
}
int main() {
cout << "Hira Fatima" << endl;
cout << "2023F-BIT-027" << endl;
cout << "\n" << endl;
const int size = 10;
int arr[size];
cout << "Enter 10 integers:" << endl;
for (int i = 0; i < size; i++) {
cin >> arr[i];
}
selectionSort(arr, size);
cout << "Sorted array:" << endl;
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;
return 0;
}
Output:
3. Create a program that take an array of 10 inputs from the user and generate the sorted
out put using the following Algorithm:
Insertion Sort
Code:
#include <iostream>
using namespace std;
void insertionSort(int arr[], int size) {
for (int i = 1; i < size; i++) {
int key = arr[i];
int j = i - 1;
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = key;
}
}
int main() {
cout << "Hira Fatima" << endl;
cout << "2023F-BIT-027" << endl;
cout << "\n" << endl;
const int SIZE = 10;
int arr[SIZE];
cout << "Please enter 10 integers: ";
for (int i = 0; i < SIZE; i++) {
cin >> arr[i];
}
insertionSort(arr, SIZE);
cout << "Sorted array in ascending order: ";
for (int i = 0; i < SIZE; i++) {
cout << arr[i] << " ";
}
cout << endl;
return 0;
}
Output :