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

Lab1 190

The document contains two programming assignments by Vansh Sharma, focusing on implementing Linear Search and Selection Sort algorithms in C++. The first program performs both linear and binary searches on an array, while the second program sorts an array using the selection sort method. Each program includes code snippets and outputs the results of the operations performed.

Uploaded by

vansh sharma
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 views5 pages

Lab1 190

The document contains two programming assignments by Vansh Sharma, focusing on implementing Linear Search and Selection Sort algorithms in C++. The first program performs both linear and binary searches on an array, while the second program sorts an array using the selection sort method. Each program includes code snippets and outputs the results of the operations performed.

Uploaded by

vansh sharma
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/ 5

Vansh Sharma

2200290110190
CSIT-5C

LAB-1

Program-1

Aim: Write a Program to implement Linear Search.


Code:
#include <iostream> using
namespace std;
int linearsearch(int arr[], int n, int key) {
for (int i = 0; i < n; i++) { if (key ==
arr[i]) { return i;
}
}
return -1;
}
int binarysearch(int arr[], int l, int u, int key) { if
(l <= u) {
int mid = l + (u - l) / 2;if (arr[mid] == key) { return
mid;

}
if (key < arr[mid]) {
return binarysearch(arr, l, mid - 1, key);
} else {
return binarysearch(arr, mid + 1, u, key);
}
}
return -1;
}
int main() {
int n, key;
cin >> n; int
arr[n];
for (int i = 0; i < n; i++) { cin
>> arr[i];
}
cin >> key;
int res1 = linearsearch(arr, n, key);int res2 = binarysearch(arr, 0, n - 1,
key);
cout << "Linear search index: " << res1 << endl; cout
<< "Binary search index: " << res2 << endl; return 0;
}
Output:
Program -2Aim: Write a program to implement 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[minIndex], 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]);
cout << "Original array: ";
printArray(arr, n);
selectionSort(arr, n); cout <<
"Sorted array: "; printArray(arr,
n); return 0;
}
Output:

You might also like