Advertisement
Guest User

Untitled

a guest
Apr 19th, 2019
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.67 KB | None | 0 0
  1. //задан отсортированный по неубыванию массив целых чисел, вывести на экран номер элемента
  2. //с заданным ключом или информацию о том, что такого элемента в масиве нет, поиск вести указанным методом.
  3.  
  4. #include "pch.h"
  5. #include <iostream>
  6. using namespace std;
  7. void SortShell(int [], int );
  8. int search(int[], int, int);
  9.  
  10. int main()
  11. {
  12. setlocale(LC_ALL, "ru");
  13. int n;
  14. cout << "Введите количество элементов массива : ";
  15. cin >> n;
  16. int *a = new int[n];
  17. cout << "Введите элементы массива : ";
  18. for (int i = 0; i < n; i++) {
  19. cin >> a[i];
  20. }
  21. SortShell(a, n);
  22. for (int i = 0; i < n; i++) {
  23. cout << " " << a[i];
  24. }
  25. cout << endl;
  26. int k;
  27. cout << "Введите ключ : ";
  28. cin >> k;
  29. if (search(a, n - 1, k) != -1) {
  30. cout << "позиция : " << search(a, n - 1, k) + 1 << " - й элементы." << endl;
  31. }
  32. else cout << "Данный элемент не был обнаружен в массиве." << endl;
  33. delete[] a;
  34. return 0;
  35. }
  36. void SortShell(int a[], int n) {
  37. int step = n / 2;
  38.  
  39. while (step != 0) {
  40.  
  41. for (int i = step; i < n; ++i) {
  42. int tmp = a[i];
  43. int j;
  44. int t;
  45. t = a[i];
  46. for (j = i - step; j >= 0 && a[j] > tmp; j = j - step)
  47.  
  48. a[j + step] = a[j];
  49.  
  50. a[j + step] = t;
  51. }
  52. step /= 2;
  53. }
  54. }
  55. //int search(int a[], int n, int x) {
  56. // a[n + 1] = x;
  57. // int i = 0;
  58. // while (a[i] != x) i++;
  59. // if (i == n + 1) return -1;
  60. // else return i;
  61. //}
  62. int search(int a[], int n, int x) {
  63. for (int i = 0; i < n; i++) {
  64. if (a[i] == x) return i;
  65. }
  66. return -1;
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement