0% found this document useful (0 votes)
10 views6 pages

Lab1 185

DAA LAB

Uploaded by

vikaspant990
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views6 pages

Lab1 185

DAA LAB

Uploaded by

vikaspant990
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

LAB 1

Name: Urvashi Rana

Roll number: 2200290110185

Sem-Sec-Group: 5 C 2

AIM: Write a program to implement Linear and Binary Search.

Linear Search:

Source Code:

#include <iostream> using

namespace std;

int linearSearch(int arr[], int n, int target) {

for (int i = 0; i < n; i++) { if (arr[i]

== target) { return i; }

return -1;

} int main() { int data[] = {12, 45, 78, 23,

56, 89, 67, 34, 90}; int n = sizeof(data) /

sizeof(data[0]); int target = 67;

int result = linearSearch(data, n, target);

if (result != -1) {

cout << "Element found at index " << result << endl;

} else {

cout << "Element not found in the array." << endl;


}

return 0;

}
Output:

Binary Search:
Source Code:

#include <iostream>

using namespace std; int

main ()

int arr[100], st, mid, end, i, num, tgt; cout <<

" Define the size of the array: " << endl; cin >>

num;

cout << " Enter the values in sorted array either ascending or descending order: "
<< endl;

for (i = 0; i < num; i++)


{

cout << " arr [" << i << "] = ";

cin >> arr[i];

} st = 0;

end = num - 1;

cout << " Define a value to be searched from sorted array: " << endl;

cin >> tgt; while ( st <= end)

mid = ( st + end ) / 2;

if (arr[mid] == tgt)

cout << " Element is found at index " << (mid + 1);

exit (0); // use for exit program the program

else if ( tgt > arr[mid])


{

st = mid + 1; // set the new value for st variable


}
else if ( tgt < arr[mid])
{

end = mid - 1; // set the new value for end variable


}
}

cout << " Number is not found. " << endl;

return 0;

Output:

AIM: Write a program to implement selection sort.


Source code: #include

<iostream> using namespace

std; void selectionSort(int arr[],

int n)

{ for (int i = 0; i < n - 1;

i++)

{ int min_idx = i;

for (int j = i + 1; j < n; j++)

{ if (arr[j] <

arr[min_idx])

min_idx = j;

} if (min_idx != i)

swap(arr[min_idx], arr[i]);

void printArray(int arr[], int n)

{ for (int i = 0; i < n; i++)

cout << arr[i] << " "; cout <<

endl; } int main() { int arr[] =

{64, 25, 12, 22, 11}; int n =

sizeof(arr) / sizeof(arr[0]);

selectionSort(arr, n); cout <<

"Sorted array: \n";

printArray(arr, n); return 0;

Output:

You might also like