You are on page 1of 5

// Code \\

#include <iostream>
#include <algorithm>

using namespace std;

int binarySearch(int arr[], int low, int high, int key) {


while (low <= high) {
int mid = low + (high - low) / 2;

if (arr[mid] == key)
return mid;

if (arr[mid] < key)


low = mid + 1;
else
high = mid - 1;
}

return -1;
}

int linearSearch(int arr[], int size, int key) {


for (int i = 0; i < size; ++i) {
if (arr[i] == key)
return i;
}

return -1;
}
void interchangeSort(int arr[], int size) {
for (int i = 0; i < size - 1; ++i) {
for (int j = i + 1; j < size; ++j) {
if (arr[i] < arr[j]) {
swap(arr[i], arr[j]);
}
}
}
}

void quickSort(int arr[], int low, int high) {


if (low < high) {
int pivot = arr[high];
int i = low - 1;

for (int j = low; j <= high - 1; j++) {


if (arr[j] > pivot) {
i++;
swap(arr[i], arr[j]);
}
}

swap(arr[i + 1], arr[high]);

int pivotIndex = i + 1;

quickSort(arr, low, pivotIndex - 1);


quickSort(arr, pivotIndex + 1, high);
}
}

int main() {
const int maxSize = 100;
int arr[maxSize];
int size;

cout << "Nhap mang: ";


cin >> size;

cout << "Nhap cac phan tu cua mang:\n";


for (int i = 0; i < size; ++i) {
cout << "Phan tu thu " << i + 1 << ": ";
cin >> arr[i];
}

int choice;
cout << "Chon chuc nang:\n";
cout << "1. Tim kiem nhi phan\n";
cout << "2. Tim kiem tuan tu\n";
cout << "3. Sap xep giam dan theo Interchange Sort\n";
cout << "4. Sap xep giam dan theo Quick Sort\n";
cout << "Nhap lua chon cua ban: ";
cin >> choice;

switch (choice) {
case 1: {
int key;
cout << "Nhap gia tri can tim kiem: ";
cin >> key;
sort(arr, arr + size);
int result = binarySearch(arr, 0, size - 1, key);
if (result != -1)
cout << "Tim thay gia tri tai vi tri " << result + 1 << endl;
else
cout << "Khong tim thay gia tri trong mang.\n";
break;
}
case 2: {
int key;
cout << "Nhap gia tri can tim kiem: ";
cin >> key;
int result = linearSearch(arr, size, key);
if (result != -1)
cout << "Tim thay gia tri tai vi tri " << result + 1 << endl;
else
cout << "Khong tim thay gia tri trong mang.\n";
break;
}
case 3: {
interchangeSort(arr, size);
cout << "Mang sau khi sap xep giam dan theo Interchange Sort:\n";
for (int i = 0; i < size; ++i)
cout << arr[i] << " ";
cout << endl;
break;
}
case 4: {
quickSort(arr, 0, size - 1);
cout << "Mang sau khi sap xep giam dan theo Quick Sort:\n";
for (int i = 0; i < size; ++i)
cout << arr[i] << " ";
cout << endl;
break;
}
default:
cout << "Lua chon khong hop le.\n";
}

return 0;
}

You might also like