Created
April 10, 2017 16:15
-
-
Save tornikegomareli/9936a77428ac866feb9bad384273012b to your computer and use it in GitHub Desktop.
3. დაწერეთ პროგრამა რომელიც 50 ელემენტიან მასივს შეავსებს რენდომ რიცხვებით. შეეკითხება მომხმარებელს ელემენტს, შემდეგ მოძებნის ამ ელემენტს Binary Search ალგორითმის მიხედვით და ჩასვავს სხვა ელემენტს მითითებულ ინდექსზე.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <stdlib.h> | |
#include <time.h> | |
using namespace std; | |
void Init(int Arr[], int Size) | |
{ | |
for (int i = 0; i < Size; i++) | |
{ | |
Arr[i] = rand() % 50; | |
} | |
} | |
void Print(int Arr[], int Size) | |
{ | |
for (int i = 0; i < Size; i++) | |
{ | |
cout << Arr[i] << " "; | |
} | |
} | |
void Sort(int Arr[], int Size) | |
{ | |
for (int i = 0; i < Size; i++) | |
{ | |
for (int j = i+1; j < Size; j++) | |
{ | |
if (Arr[i] > Arr[j]) | |
{ | |
int tmp = Arr[i]; | |
Arr[i] = Arr[j]; | |
Arr[j] = tmp; | |
} | |
} | |
} | |
} | |
int binarySearch(int Arr[], const int Size, int Value) | |
{ | |
int left = 0; | |
int right = Size; | |
while (left <= right) | |
{ | |
int middle = (left + right) / 2; | |
if (Arr[middle] == Value) | |
return middle; | |
else if (Arr[middle] < Value) | |
left = middle + 1; | |
else | |
right = middle - 1; | |
} | |
return -1; | |
} | |
int main() | |
{ | |
const int Size = 50; | |
int Array[Size]; | |
int Value, Insert; | |
Init(Array, Size); // Initialization | |
Sort(Array, Size); // Sorting with Selection sort | |
Print(Array, Size); // Print | |
cout << "\n"; | |
cout << " Enter value which you want to change "; | |
cin >> Value; | |
cout << " Enter value which you want to Insert : "; | |
cin >> Insert; | |
int Index = binarySearch(Array, Size, Value); | |
if (Index != -1) | |
{ | |
cout << " Your Number changed to : "; | |
Array[Index] = Insert; | |
cout << Array[Index] << endl; | |
} | |
else | |
cout << " Your number is not in Array "; | |
cout << "\n"; | |
Print(Array, Size); | |
cin.get(); | |
cin.get(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment