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

NATIONAL UNIVERSITY

OF
MODERN LANGUAGES

DATA STRUCTURES & ALGORITHMS


LAB REPORTS

NAME: Ayesha Akram


ROLL NO: 12362
CLASS: BSSE (3-A)
SUBMITTED TO: Ma’am Huma Nadeem
LAB REPORT # 08
TASK 1:
Define and implement a method BubbleSort with arrays. Enter 15 values from user and
perform bubble sort(order) on them in acsending and descending order.
PROGRAM:
#include<iostream>
using namespace std;
void bubblesort(int n,int *array)
{
for(int i = 1; i<=n-1; i++)
{
for(int j = 0; j<=n-i-1; j++)
{
if(array[j] > array[j+1])
swap(array[j], array[j+1]);
}
}
}
void swap(int &i, int &j)
{
int temp;
temp = i;
i = j;
j = temp;
}
void display(int *array, int n)
{
for(int i = 0; i<n; i++)
cout << array[i] << " ";
cout<<endl;
}
void descdisplay(int *array, int n){
for(int i = n-1; i>=0; i--)
cout << array[i] << " ";
}
int main()
{
int n;
cout<<"Enter the number of elements : ";
cin>>n;
int array[n];
cout<<"Enter the elements of the array :\n";
for (int i=0;i<n;i++)
{
cin>>array[i];
}
char x;
cout<<"Do you want to sort the array in acsending order or descending order (a/d)? ";
cin>>x;
if (x=='a')
{
cout << "Array before Sorting: ";
display(array, n);
bubblesort(n,array);
cout << "Array after Sorting: ";
display(array, n);
}
else if(x=='d')
{
cout << "Array before Sorting: ";
display(array, n);
bubblesort(n,array);
cout << "Array after Sorting : ";
descdisplay(array, n);
}
}
TASK 2:
Display values in ascending order via SelectionSort() method.
PROGRAM:
#include<iostream>
using namespace std;
void selectionSort(int *array, int n) {
int min;
for(int i = 0; i<n-1; i++) {
min = i;
for(int j = i+1; j<n; j++)
if(array[j] < array[min])
min = j;
swap(array[i], array[min]);
}
}
void swap(int &i, int &j)
{
int temp;
temp = i;
i = j;
j = temp;
}
void display(int *array, int n)
{
for(int i = 0; i<n; i++)
cout << array[i] << " ";
cout<<endl;
}
void descdisplay(int *array, int n)
{
for(int i = n-1; i>=0; i--)
cout << array[i] << " ";
}
int main()
{
int n;
cout<<"Enter the number of elements : ";
cin>>n;
int array[n];
cout<<"Enter the elements of the array :\n";
for (int i=0;i<n;i++)
{
cin>>array[i];
}
char x;
cout<<"Do you want to sort the array in acsending order or descending order (a/d)? ";
cin>>x;
if (x=='a')
{
cout << "Array before Sorting: ";
display(array, n);
selectionSort(array,n);
cout << "Array after Sorting: ";
display(array, n);
}
else if(x=='d')
{
cout << "Array before Sorting: ";
display(array, n);
selectionSort(array, n);
cout << "Array after Sorting : ";
descdisplay(array, n);
}
}

You might also like