Question: COMMENT ON the code below .what does each part do for the program? #include #include using namespace std; void swap(int *xp, int *yp) { int
COMMENT ON the code below .what does each part do for the program?
#include
void swap(int *xp, int *yp) { int temp = *xp; *xp = *yp; *yp = temp; } void printArray(int arr[], int size) { int i; for (i=0; i < size; i++) printf("%d ", arr[i]); printf(" "); } void bubbleSort(int numbers[], int n) { int i, j, count = 0; for (i = 0; i < n-1; i++) for (j = 0; j < n-i-1; j++) if (numbers[j] > numbers[j+1]){ swap(&numbers[j], &numbers[j+1]); count++; } cout << "No of exchanges in bubble sort is " << count << endl; }
void selectionSort(int numbers2[], int n) { int i, j, min_idx, count = 0; for (i = 0; i < n-1; i++) { min_idx = i; for (j = i+1; j < n; j++) if (numbers2[j] < numbers2[min_idx]) min_idx = j; swap(&numbers2[min_idx], &numbers2[i]); count++; } cout << "No of exchanges in selection sort is " << count << endl; } void linearSearch(int numbers[]){ int count = 0; for(int i = 0; i < 200; i++){ count++; if(numbers[i] == 869) break; } cout << "No of comparisons in linear search is " << count << endl; } int binarySearch(int numbers[], int l, int r, int x, int count) { if (r >= l) { count++; int mid = l + (r - l)/2; if (numbers[mid] == x) return count; if (numbers[mid] > x) return binarySearch(numbers, l, mid-1, x, count); return binarySearch(numbers, mid+1, r, x, count); } return -1; } int main() { fstream myfile("data.txt", std::ios_base::in); int a, numbers[200], count = -1; while (myfile >> a) { count++; numbers[count] = a; } int numbers2[200]; for(int i = 0; i < 200; i++) numbers2[i] = numbers[i]; bubbleSort(numbers, 200); selectionSort(numbers2, 200); linearSearch(numbers); int res = binarySearch(numbers,0, 199, 869, 0); cout << "No of comparisons in binary search is " << res << endl; return 0; }
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
