Напечатать список студентов строго в порядке уменьшения возраста. "Приостановить" быструю сортировку - C#
Формулировка задачи:
Здравствуйте. Подскажите, как мне отсортировать массив быстрой сортировкой до кусочков, меньших 3? То есть приостановить ее на этом моменте. Код сортировки ниже, вся программа с условием задачи еще ниже под спойлером.
Я так понимаю, мне нужно вставить условие Math.Abs(a-b) > 2. Пробовал в разных местах, но так как не представляю, как в идеале должен выглядеть массив, отсортированный быстрой сортировкой до кусочков, меньших 3, полагаться на свои знания не могу.
Заранее благодарю за ответ
public static void QuickSort(Students[] arr, int start, int end)
{
int point = arr[(start + end) / 2].data;
int a = start, b = end;
while (a <= b)
{
while (arr[a].data < point) a++;
while (arr[b].data > point) b--;
if (a <= b)
{
Students temp = arr[a];
arr[a] = arr[b];
arr[b] = temp;
a++; b--;
}
}
if ((a < end)) { QuickSort(arr, a, end); }
if ((start < b)) { QuickSort(arr, start, b); }
}using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
struct Students
{
public string lastname; // Фамилия
public string initials; // Инициалы
public int day; // День рождения
public int month; // Месяц рождения
public int year; // Год рождения
public int data; // Дата рождения в формате ггггммдд
}
namespace StudentsSort
{
class Program
{
static void ArrayFromTxtFile(Students[] arr)
{
string InPath = "TxtFiles/in.txt";
StreamReader sr = new StreamReader(InPath, Encoding.GetEncoding(1251));
string line;
int i = 0;
while ((line = sr.ReadLine()) != null)
{
string[] s = line.Split(' ');
arr[i].lastname = s[0];
arr[i].initials = s[1];
s = line.Split('.');
arr[i].day = int.Parse(s[2]);
arr[i].month = int.Parse(s[3]);
arr[i].year = int.Parse(s[4]);
arr[i].data = arr[i].year * 10000 + arr[i].month * 100 + arr[i].day; // Формируем числовую запись даты рождения в формате ггггммдд
i++;
}
sr.Close();
}
public static void QuickSort(Students[] arr, int start, int end)
{
int point = arr[(start + end) / 2].data;
int a = start, b = end;
while (a <= b)
{
while (arr[a].data < point) a++;
while (arr[b].data > point) b--;
if (a <= b)
{
Students temp = arr[a];
arr[a] = arr[b];
arr[b] = temp;
a++; b--;
}
}
if ((a < end)) { QuickSort(arr, a, end); }
if ((start < b)) { QuickSort(arr, start, b); }
}
public static void ShellSort(Students[] arr)
{
int point = arr.Length;
while (point > 0)
{
for (int i = 0; i < arr.Length - point; i++)
{
int j = i;
while ((j >= 0) && (arr[j + point].data < arr[j].data))
{
Students temp = arr[j];
arr[j] = arr[j + point];
arr[j + point] = temp;
j--;
}
}
point /= 2;
}
}
static void PrintArray(Students[] arr, int LineCount) // Вывод на экран
{
for (int i = 0; i < LineCount; i++)
{
Console.Write("{0} {1}\t", arr[i].lastname, arr[i].initials);
if (arr[i].day < 10) { Console.Write("0{0}.", arr[i].day); } else { Console.Write("{0}.", arr[i].day); }
if (arr[i].month < 10) { Console.Write("0{0}.", arr[i].month); } else { Console.Write("{0}.", arr[i].month); }
Console.WriteLine("{0}", arr[i].year);
}
}
static void SaveArrayInTxtFile(Students[] arr, int LineCount) // Печать в файл
{
string OutPath = "TxtFiles/out.txt";
StreamWriter sw = new StreamWriter(OutPath);
for (int i = 0; i < LineCount; i++)
{
sw.Write("{0} {1}\t", arr[i].lastname, arr[i].initials);
if (arr[i].day < 10) { sw.Write("0{0}.", arr[i].day); } else { sw.Write("{0}.", arr[i].day); }
if (arr[i].month < 10) { sw.Write("0{0}.", arr[i].month); } else { sw.Write("{0}.", arr[i].month); }
sw.WriteLine("{0}", arr[i].year);
}
sw.Close();
}
static void Main(string[] args)
{
int LineCount = File.ReadLines("in.txt").Count(); // Записываем в переменную LineCount количество строк в файле in.txt в папке с программой
Students[] Array = new Students[LineCount]; // Создаем структуру
ArrayFromTxtFile(Array); // Заполняем структуру данными из файла in.txt в папке с программой
Console.WriteLine("\n\tБаза данных студентов до упорядочивания" + "\n");
PrintArray(Array, LineCount); // Выводим на экран исходные данные
QuickSort(Array, 0, LineCount - 1); // Сортируем методом "Быстрой сортировки"
ShellSort(Array); // Сортируем методом "Шелла"
System.Array.Reverse(Array); // Инвертируем массив, чтобы он был в порядке убывания
Console.WriteLine("\n\tБаза данных студентов после упорядочивания" + "\n");
PrintArray(Array, LineCount); // Выводим на экран отсортированный массив
SaveArrayInTxtFile(Array, LineCount); // Сохраняем полученный массив в файл out.txt в папке с программой
Console.ReadKey();
}
}
}Решение задачи: «Напечатать список студентов строго в порядке уменьшения возраста. "Приостановить" быструю сортировку»
textual
Листинг программы
public static void QuickSortPartial(Students[] arr, int start, int end, int range = 3)
{
if (end - start <= range)
return;
int point = arr[(start + end) / 2].data;
int a = start, b = end;
while (a <= b)
{
while (arr[a].data < point) a++;
while (arr[b].data > point) b--;
if (a <= b)
{
Students temp = arr[a];
arr[a] = arr[b];
arr[b] = temp;
a++; b--;
}
}
if ((a < end)) { QuickSort(arr, a, end); }
if ((start < b)) { QuickSort(arr, start, b); }
}