M9 Account
unknown
c_cpp
2 years ago
2.4 kB
10
Indexable
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
void bubbleSort(int arr[], int n) {
for (int i = 0; i < n - 1; ++i) {
for (int j = 0; j < n - i - 1; ++j) {
if (arr[j] > arr[j + 1]) {
// Swap arr[j] and arr[j + 1]
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;
}
bool linearSearch(int arr[], int n, int target) {
for (int i = 0; i < n; ++i) {
if (arr[i] == target) {
// Account number is valid
return true;
}
}
// Account number is invalid
return false;
}
bool binarySearch(int arr[], int n, int target) {
int low = 0, high = n - 1;
while (low <= high) {
int mid = low + (high - low) / 2;
if (arr[mid] == target) {
// Account number is valid
return true;
} else if (arr[mid] < target) {
low = mid + 1;
} else {
high = mid - 1;
}
}
// Account number is invalid
return false;
}
int main() {
int acctList[18] = {
8149420, 5333174, 3080098, 6755963, 9526981, 4449539, 9387197, 5104726, 2931356,
4282637, 1750219, 6086650, 3164838, 2419590, 4578589, 9718904, 6749941, 2545408
};
int n = sizeof(acctList) / sizeof(acctList[0]);
// Display unsorted array
cout << "Original array: ";
printArray(acctList, n);
// Perform bubble sort
bubbleSort(acctList, n);
// Display sorted array
cout << "\nSorted array: ";
printArray(acctList, n);
// User enters a number
int userAccountNumber;
cout << "Enter a charge account number: ";
cin >> userAccountNumber;
// Perform linear search
if (linearSearch(acctList, n, userAccountNumber)) {
cout << "Account number is valid (linear search)." << endl;
} else {
cout << "Account number is invalid (linear search)." << endl;
}
// Perform binary search
if (binarySearch(acctList, n, userAccountNumber)) {
cout << "Account number is valid (binary search)." << endl;
} else {
cout << "Account number is invalid (binary search)." << endl;
}
return 0;
}
Editor is loading...
Leave a Comment