Исправил код по замечаниям:

- Опорная точка выбирается случайным образом.
- Убрал лишнее создание копии списка.
- Доработал проверки корректности входных данных.
This commit is contained in:
Leonid
2025-05-07 10:05:18 +03:00
parent 607e827256
commit d7d53d5fa0
2 changed files with 21 additions and 8 deletions

View File

@@ -20,10 +20,6 @@ public class ExcelProcessorService {
public Integer findNthSmallest(MultipartFile file, int n) throws IOException { public Integer findNthSmallest(MultipartFile file, int n) throws IOException {
List<Integer> numbers = excelReader.readNumbersFromFirstColumn(file); List<Integer> numbers = excelReader.readNumbersFromFirstColumn(file);
if (n < 1 || n > numbers.size()) {
throw new IllegalArgumentException("Некорректный порядковый номер N");
}
return QuickSelect.findNthSmallest(numbers, n); return QuickSelect.findNthSmallest(numbers, n);
} }
} }

View File

@@ -1,15 +1,30 @@
package com.example.excelprocessor.util; package com.example.excelprocessor.util;
import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Objects;
import java.util.Random;
public class QuickSelect { public final class QuickSelect {
private static final Random random = new Random();
public static int findNthSmallest(List<Integer> numbers, int n) { public static int findNthSmallest(List<Integer> numbers, int n) {
List<Integer> copyList = new ArrayList<>(numbers); validateNumbersNotEmpty(numbers);
return quickSelect(copyList, 0, copyList.size() - 1, n - 1);
if (n < 1 || n > numbers.size()) {
throw new IllegalArgumentException("Некорректный порядковый номер N");
}
return quickSelect(numbers, 0, numbers.size() - 1, n - 1);
}
private static void validateNumbersNotEmpty(List<Integer> numbers) {
if (Objects.isNull(numbers) || numbers.isEmpty()) {
throw new IllegalArgumentException("Список не может быть пустым");
}
} }
private static int quickSelect(List<Integer> numbers, int from, int to, int n) { private static int quickSelect(List<Integer> numbers, int from, int to, int n) {
@@ -31,6 +46,8 @@ public class QuickSelect {
private static int partition(List<Integer> list, int from, int to) { private static int partition(List<Integer> list, int from, int to) {
int pivotIdx = from + random.nextInt(to - from + 1);
Collections.swap(list, pivotIdx, to);
int currIdx = from; int currIdx = from;
int pivot = list.get(to); int pivot = list.get(to);