Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<iostream>
- #include<ctime>
- using namespace std;
- int binarySearch(double *vectorA, int n,double value)
- {
- int index;
- int left=0, right=n-1;
- while (left <= right)
- {
- index = (left + right) / 2;
- if (vectorA[index] == value) {
- return index;
- }
- if (vectorA[index] > value) {
- right = index - 1;
- }
- else {
- left = index + 1;
- }
- }
- return -1;
- }
- void bubbleSort(double *vectorA,int n) //sortujemy elementy wektora(rosnaco) za pomoca sortowanie babelkowego
- {
- for (int i = 0; i<n; i++)
- for (int j = 1; j<n - i; j++)
- if (vectorA[j - 1]>vectorA[j])
- swap(vectorA[j - 1], vectorA[j]);
- }
- void setVectorValue(double*vectorA,int n)
- {
- for (int i = 0; i < n; i++)
- {
- vectorA[i] = rand() % 101; //uzupelniamy wektor wartosciami od 0 do 100
- }
- }
- void showVector(double *vectorA, int n)
- {
- for (int i = 0; i < n; i++)
- {
- cout << vectorA[i] << endl;
- }
- }
- int main() {
- int n;
- double value;
- double *vectorA;
- cout << "Podaj liczbe elementow wektora\n";
- cin >> n;
- vectorA = new double[n];
- setVectorValue(vectorA,n);
- cout << "Przed sortowaniem\n";
- showVector(vectorA, n);
- cout << endl;
- cout << "Po sortowaniu\n";
- bubbleSort(vectorA, n);
- showVector(vectorA, n);
- cout << "Podaj wartosc szukanego elementu\n";
- cin >> value;
- if (binarySearch(vectorA, n, value) == -1)
- {
- cout << "Nie ma takiego elementu...Funkcja zwraca wartosc:\n";
- cout << binarySearch(vectorA, n, value);
- cout << endl;
- }
- else
- {
- cout << "Indeks szukanego elementu to...\n";
- cout << binarySearch(vectorA, n, value);
- cout << endl;
- }
- system("pause");
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement