Advertisement
Mevent

Mevent. Laboratory work. Option 11

Nov 19th, 2023
134
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.96 KB | None | 0 0
  1. #include<iostream>
  2.  
  3. using namespace std;
  4.  
  5. // О(n2)
  6. void selectionSort(int arr[], int size) {
  7. for (int i = 0; i < size - 1; i++) {
  8. // устанавливаем начальное значение минимального индекса
  9. int minIndex = i;
  10.  
  11. // находим индекс минимального элемента
  12. for (int j = i + 1; j < size; j++) {
  13. if (arr[j] < arr[minIndex]) {
  14. minIndex = j;
  15. }
  16. }
  17.  
  18. // меняем значения местами
  19. if (minIndex != i) {
  20. std::swap(arr[i], arr[minIndex]);
  21. }
  22. }
  23. }
  24.  
  25. int linearSearch(int arr[], int n, int key) {
  26. for (int i = 0; i < n; i++) {
  27. if (arr[i] == key) {
  28. return i; // возвращаем индекс первого вхождения
  29. }
  30. }
  31. return -1; // возвращаем -1, если элемент не найден
  32. }
  33.  
  34. int linearSearch(std::string arr[], int n, std::string key) {
  35. for (int i = 0; i < n; i++) {
  36. if (arr[i] == key) {
  37. return i; // возвращаем индекс первого вхождения
  38. }
  39. }
  40. return -1; // возвращаем -1, если элемент не найден
  41. }
  42.  
  43. int main()
  44. {
  45. int arr[] = {64, 25, 12, 22, 11};
  46. int n = sizeof(arr) / sizeof(arr[0]);
  47. selectionSort(arr, n);
  48. std::cout << "Sorted array: ";
  49. for (int i = 0; i < n; i++) {
  50. std::cout << arr[i] << " ";
  51. }
  52. std::cout << std::endl;
  53.  
  54. int intArr[] = {1, 2, 3, 4, 5};
  55. std::string strArr[] = {"яблоко", "банан", "вишня", "дата", "бузина"};
  56. int intIndex = linearSearch(intArr, 5, 3);
  57. int strIndex = linearSearch(strArr, 5, "вишня");
  58. std::cout << "Index of 3 in intArr: " << intIndex << std::endl;
  59. std::cout << "Index of 'вишня' in strArr: " << strIndex << std::endl;
  60.  
  61. return 0;
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement