Lab6 193
Lab6 193
Sem-Sec-Group: 5 C 2
Ternary Search :
Source Code :
#include <iostream>
using namespace std;
int ternarySearch(int arr[], int left, int right, int key) {
while (left <= right)
int mid1 = left + (right - left) / 3;
int mid2 = right - (right - left) / 3;
if (arr[mid1] == key) {
return mid1;
}
if (arr[mid2] == key) {
return mid2;
}
if (key < arr[mid1]) {
right = mid1 - 1;
}
else if (key > arr[mid2]) {
left = mid2 + 1;
}
else {
left = mid1 + 1;
right = mid2 - 1;
}
}
return -1;
}
int main() {
int n, key;
cout << "Enter the number of elements in the array: ";
cin >> n;
int arr[n];
cout << "Enter " << n << " sorted elements: ";
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
cout << "Enter the element to search for: ";
cin >> key;
int result = ternarySearch(arr, 0, n - 1, key);
if (result != -1) {
cout << "Element found at index: " << result << endl;
} else {
cout << "Element not found in the array." << endl;
}
return 0;
}
Output:
AIM: Write a program to Search in Rotated Array.
Source Code :
#include <iostream>
if (arr[mid] == key) {
return mid;
right = mid - 1;
} else {
left = mid + 1;
else {
left = mid + 1;
} else {
right = mid - 1;
return -1;
}
int main() {
int n, key;
cin >> n;
int arr[n];
cout << "Enter " << n << " elements of the rotated sorted array: ";
if (result != -1) {
cout << "Element found at index: " << result << endl;
} else {
return 0;
}
Output :
AIM: Write a program to implement Inversion Count.
Inversion Count :
Source Code :
#include <iostream>
using namespace std;
int mergeAndCount(int arr[], int temp[], int left, int mid, int right) {
int i = left; // Starting index for left subarray
int j = mid + 1; // Starting index for right subarray
int k = left; // Starting index to be sorted
int inv_count = 0;
while (i <= mid && j <= right) {
if (arr[i] <= arr[j]) {
temp[k++] = arr[i++];
} else {
temp[k++] = arr[j++];
inv_count += (mid - i + 1);
}
}
while (i <= mid) {
temp[k++] = arr[i++];
}
while (j <= right) {
temp[k++] = arr[j++];
}
for (i = left; i <= right; i++) {
arr[i] = temp[i];
}
return inv_count;
}
int mergeSortAndCount(int arr[], int temp[], int left, int right) {
int mid, inv_count = 0;
if (left < right) {
mid = (left + right) / 2;
inv_count += mergeSortAndCount(arr, temp, left, mid);
inv_count += mergeSortAndCount(arr, temp, mid + 1, right);
inv_count += mergeAndCount(arr, temp, left, mid, right);
}
return inv_count;
}
int countInversions(int arr[], int n) {
int temp[n];
return mergeSortAndCount(arr, temp, 0, n - 1);
}
int main() {
int n;
cout << "Enter the number of elements in the array: ";
cin >> n;
int arr[n];
cout << "Enter the elements of the array: ";
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
int inversionCount = countInversions(arr, n);
cout << "Number of inversions: " << inversionCount << endl;
return 0;
}
Source Code :