[csharp] kakolimp84
Viewer
- using System;
- class Program
- {
- // Сортировка выбором
- static void SelectionSort(int[] arr)
- {
- int n = arr.Length;
- for (int i = 0; i < n - 1; i++)
- {
- int minIndex = i;
- for (int j = i + 1; j < n; j++)
- {
- if (arr[j] < arr[minIndex])
- {
- minIndex = j;
- }
- }
- // Обмен элементов
- int temp = arr[minIndex];
- arr[minIndex] = arr[i];
- arr[i] = temp;
- // Вывод массива после каждого шага
- Console.Write($"Шаг {i + 1}: ");
- PrintArray(arr);
- }
- }
- // Бинарный поиск
- static int BinarySearch(int[] arr, int target)
- {
- int left = 0;
- int right = arr.Length - 1;
- while (left <= right)
- {
- int mid = left + (right - left) / 2;
- if (arr[mid] == target)
- {
- return mid;
- }
- else if (arr[mid] < target)
- {
- left = mid + 1;
- }
- else
- {
- right = mid - 1;
- }
- }
- // Если элемент не найден
- return -1;
- }
- // Представление односвязного списка и вставка элемента после первого элемента
- class ListNode
- {
- public int Value { get; set; }
- public ListNode Next { get; set; }
- public ListNode(int value)
- {
- Value = value;
- Next = null;
- }
- }
- static ListNode InsertAfterFirst(ListNode head, int value)
- {
- ListNode newNode = new ListNode(value);
- if (head == null)
- {
- return newNode;
- }
- newNode.Next = head.Next;
- head.Next = newNode;
- return head;
- }
- static void PrintList(ListNode head)
- {
- ListNode current = head;
- while (current != null)
- {
- Console.Write($"{current.Value} ");
- current = current.Next;
- }
- Console.WriteLine();
- }
- static void PrintArray(int[] arr)
- {
- foreach (var item in arr)
- {
- Console.Write($"{item} ");
- }
- Console.WriteLine();
- }
- static void Main(string[] args)
- {
- int[] arr = { 2, 3, 10, 5, 7, 6, 4, 12, 20, 9, 11, 22, 24, 25 };
- Console.WriteLine("Исходный массив:");
- PrintArray(arr);
- Console.WriteLine("\nТрассировка первых 10 шагов (обменов) сортировки выбором:");
- SelectionSort(arr);
- Console.WriteLine("\nРезультат сортировки:");
- PrintArray(arr);
- int target = 20;
- Console.WriteLine($"\nПоиск числа {target} методом бинарного поиска:");
- int index = BinarySearch(arr, target);
- if (index != -1)
- {
- Console.WriteLine($"Число {target} найдено в позиции {index}.");
- }
- else
- {
- Console.WriteLine($"Число {target} не найдено в массиве.");
- }
- // Создание односвязного списка и вставка элемента после первого элемента
- ListNode head = new ListNode(1);
- head = InsertAfterFirst(head, 2);
- head = InsertAfterFirst(head, 3);
- Console.WriteLine("\nОдносвязный список после вставки элемента:");
- PrintList(head);
- }
- }
Editor
You can edit this paste and save as new: