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

Department of Computer Science

Exercises/Lab Journal 7

Task 1.
Write a program that sorts following arrays using bubble sort.

3 1 4 1 5 9 2 6 5

2 10 14 11 13 82 4

1 3 4 9 7 2 22 31 13 22 11

Your program should follow the sequence of actions given below.


- Declare and initialize the three arrays
- Sort first array, print the sorted array
- Sort second array, print the sorted array
- Sort third array, print the sorted array
- Identify Median value of each array and display it.

Code:
#include <iostream>
using namespace std;
int main()
{
int med1, med2, med3;

//Declaring and initializing three arrays:


int a[9] = { 3,1,4,1,5,9,2,6,5 };
int b[7] = { 2,10,14,11,13,82,4 };
int c[11] = { 1,3,4,9,7,2,22,31,13,22,11 };

//Code to sort and print the first array:


for (int i = 0; i < 9; i++)
{
for (int j = 0; j < 9; j++)
{
if (a[i] < a[j])
{
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
cout << "The First sorted array is " ;

for (int i = 0; i < 9; i++)


{
cout << "\t" << a[i];

}
cout << endl << endl;

//Code to sort and print the Second array:

for (int i = 0; i < 7; i++)


{
for (int j = 0; j < 7; j++)
{
if (b[i] < b[j])
{
int temp = b[i];
b[i] = b[j];
b[j] = temp;
}
}
}

cout << "The second sorted array is " ;


for (int i = 0; i < 7; i++)
{
cout << "\t" << b[i];
}

cout << endl << endl;

//Code to sort and print the Third array:

for (int i = 0; i < 11; i++)


{
for (int j = 0; j < 11; j++)
{
if (c[i] < c[j])
{
int temp = c[i];
c[i] = c[j];
c[j] = temp;
}
}
}
cout << "The Thrid sorted array is ";
for (int i = 0; i < 11; i++)
{
cout << "\t" << c[i] ;
}

cout << endl << endl;

med1 = a[(9 - 1) / 2];


cout << "median of First sorted array is " << med1 << endl << endl;
med2 = b[(7 - 1) / 2];
cout << "median of Second sorted array is " << med2 << endl << endl;
med3 = c[(11 - 1) / 2];
cout << "median of Third sorted array is " << med3 << endl << endl;

return 0;
}

Output:
-

Task 2.
Write a program that finds out if a value given by user is present in an array or not, you can use linear search
or binary search for this problem.

12 16 4 0 52 93 22 64 50

Code:
#include <iostream>
using namespace std;
int linearSearch(int[9]);
int main()
{
const int arr[9] = { 12,16,4,0,52,93,22,64,50 };
int a = -1, searchKey;

cout << "Enter integer search key : " << endl;


cin >> searchKey;
for (int n = 0; n < 9; n++)
{
if (arr[n] == searchKey)
{
a = 0 + n;
}
}
cout << endl;

if (a >= 0)
{
cout << "found the value " << searchKey << " at index " << a;
}

else
{
cout << "value not found";
}
cout << endl;

return 0;
}
Output when value found:

Output when value not found:

You might also like