Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Упражнение 1: Задачa 2
- #include <iostream>
- #include <vector>
- #define SIZE 200
- using namespace std;
- int binarySearch( int searchElement, int data[], int length)
- {
- int low = 0;
- int high = length - 1;
- int middle = ( low + high + 1 ) / 2;
- int location = -1;
- do {
- if ( searchElement == data[ middle ] ){
- location = middle;
- }
- else if ( searchElement < data[ middle ] ) {
- high = middle - 1;
- }
- else {
- low = middle + 1;
- }
- middle = ( low + high + 1 ) / 2;
- } while ( ( low <= high ) && ( location == -1 ) );
- return location;
- }
- int bubbleSort(int arr[], int n)
- {
- int cnt = 0;
- 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], arr[j+1]);
- cnt++;
- }
- }
- }
- return cnt;
- }
- int main() {
- int nums[SIZE], cpnums[SIZE];
- int n;
- do{
- cout << "Enter number of elements: ";
- cin >> n;
- } while (n <= 0 || n > SIZE);
- for (int i = 0; i < n; i++){
- cin >> nums[i];
- }
- // copy array
- for (int i = 0; i < n; i++){
- cpnums[i] = nums[i];
- }
- cout << "Swaps count: " << bubbleSort(cpnums, n) << endl;
- int m;
- cout << "Enter element for search: ";
- cin >> m;
- if(binarySearch(m, cpnums, n) == -1){
- cout << "Not found!" << endl;
- } else {
- cout << m << " is found" << endl;
- vector<int> indexes; // dynamic array (vector)
- for (int i = 0; i < n; i++) {
- if (nums[i] == m){
- indexes.push_back(i);
- }
- }
- cout << "Indexes: ";
- for (vector<int>::iterator it = indexes.begin() ; it != indexes.end(); ++it){
- cout << *it << ", ";
- }
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement