Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 6

DSA LAB

LAB REPORT 12

Submitted By:
M.ALI ARIF
F20604037

Submitted To:
Dr. Umair/ Engr. Abdul Qadeer

DEPARTMENT OF COMPUTER ENGINEERING


Lab Tasks:
Task 1: Write a code to sort the following arrays using selection sort method.

[10, 34, 2, 56,7,67, 88, 42]

Code:
//Muhammad Ali Arif
//F20604037
#include <iostream>
using namespace std;
void selectionSort(int arr[], int n) {
int i, j, min_idx;

for (i = 0; i < n-1; i++) {


min_idx = i;
for (j = i+1; j < n; j++) {
if (arr[j] < arr[min_idx])
min_idx = j;
}
swap(arr[i], arr[min_idx]);
}
}
int main() {
int arr[] = {10, 34, 2, 56, 7, 67, 88, 42};
int n = sizeof(arr)/sizeof(arr[0]);

selectionSort(arr, n);
cout << "Sorted array: ";
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
cout << endl;
return 0;
}
OUTPUT:

Write a code to sort the following arrays using bubble sort method.

[10, 34, 2, 56, 7, 67, 88, 42]


Code:
//Muhammad Ali Arif
//F20604037
#include <iostream>
using namespace std;

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


int i, j;
bool swapped;
for (i = 0; i < n-1; i++) {
swapped = false;
for (j = 0; j < n-i-1; j++) {
if (arr[j] > arr[j+1]) {
swap(arr[j], arr[j+1]);
swapped = true;
}
}
if (swapped == false)
break;
}
}

int main() {
int arr[] = {10, 34, 2, 56, 7, 67, 88, 42};
int n = sizeof(arr)/sizeof(arr[0]);

bubbleSort(arr, n);

cout << "Sorted array: ";


for (int i = 0; i < n; i++)
cout << arr[i] << " ";
cout << endl;
return 0;
}
OUTPUT:
Post Lab Task:
One possible improvement for Bubble Sort would be to add a flag variable
and a test that determines if an exchange was made during the current
iteration. If no exchange was made, then the list is sorted and so the
algorithm can stop early. This makes the best case performance become O(n)
(because if the list is already sorted, then no iterations will take place on the
first pass, and the sort will stop right there).Modify the Bubble Sort
implementation to add this flag and test. Compare the modified
implementation on a range of inputs to determine if it does or does not
improve performance in practice.
Code:
//Mhammad Ali Arif
//F20604037
#include <iostream>
using namespace std;
void bubbleSort(int arr[], int n) {
bool swapped = true; // initialize swapped to true
int i = 0;
while (swapped) {
swapped = false;
for (int j = 0; j < n-i-1; j++) {
if (arr[j] > arr[j+1]) {
// swap arr[j] and arr[j+1]
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
swapped = true; // set swapped to true if an exchange was made
}
}
i++;
}
}
int main() {
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(arr)/sizeof(arr[0]);
bubbleSort(arr, n);
cout << "Sorted array: \n";
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
cout << endl;
return 0;
}
Output:

You might also like