Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 23 additions & 10 deletions src/main/java/com/thealgorithms/sorts/StrandSort.java
Original file line number Diff line number Diff line change
Expand Up @@ -37,20 +37,33 @@ private static <T extends Comparable<? super T>> List<T> strandSort(List<T> list

List<T> result = new ArrayList<>();
while (!list.isEmpty()) {
final List<T> sorted = new ArrayList<>();
sorted.add(list.removeFirst());
for (int i = 0; i < list.size();) {
if (sorted.getLast().compareTo(list.get(i)) <= 0) {
sorted.add(list.remove(i));
} else {
i++;
}
}
result = merge(result, sorted);
List<T> strand = extractStrand(list);
result = merge(result, strand);
}
return result;
}

/**
* Extracts the next non-decreasing subsequence (strand) from the remaining unsorted list,
* removing each selected element from {@code unsorted}.
*
* @param <T> The type of elements to be sorted, must be Comparable.
* @param unsorted The remaining unsorted elements (must be non-empty).
* @return A non-decreasing strand extracted in a single pass.
*/
private static <T extends Comparable<? super T>> List<T> extractStrand(List<T> unsorted) {
final List<T> strand = new ArrayList<>();
strand.add(unsorted.removeFirst());
for (int i = 0; i < unsorted.size();) {
if (strand.getLast().compareTo(unsorted.get(i)) <= 0) {
strand.add(unsorted.remove(i));
} else {
i++;
}
}
return strand;
}

/**
* Merges two sorted lists into one sorted list.
*
Expand Down
62 changes: 62 additions & 0 deletions src/test/java/com/thealgorithms/sorts/StrandSortTest.java
Original file line number Diff line number Diff line change
@@ -1,8 +1,70 @@
package com.thealgorithms.sorts;

import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertSame;

import java.util.Arrays;
import java.util.List;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;

class StrandSortTest extends SortingAlgorithmTest {
@Override
SortAlgorithm getSortAlgorithm() {
return new StrandSort();
}

@Test
@DisplayName("Refactor fixture: locks down ascending ordering, duplicates, smallest collections, and in-place array return")
void testFixtureBehaviorPreserved() {
StrandSort sorter = new StrandSort();

// Smallest supported collections: empty and single-element arrays
Integer[] empty = new Integer[] {};
Integer[] emptyResult = sorter.sort(empty);
assertSame(empty, emptyResult, "toArray(array) preserves the array instance");
assertArrayEquals(new Integer[] {}, emptyResult);

Integer[] single = new Integer[] {1};
Integer[] singleResult = sorter.sort(single);
assertSame(single, singleResult);
assertArrayEquals(new Integer[] {1}, singleResult);

// Fixture: [3, 1, 2] -> [1, 2, 3]
Integer[] mixed = new Integer[] {3, 1, 2};
Integer[] mixedResult = sorter.sort(mixed);
assertSame(mixed, mixedResult);
assertArrayEquals(new Integer[] {1, 2, 3}, mixedResult);

// Fixture: [2, 2, 1] -> [1, 2, 2]
Integer[] duplicates = new Integer[] {2, 2, 1};
Integer[] duplicatesResult = sorter.sort(duplicates);
assertSame(duplicates, duplicatesResult);
assertArrayEquals(new Integer[] {1, 2, 2}, duplicatesResult);

// Fixture: already ordered [1, 2, 3] -> [1, 2, 3]
Integer[] ordered = new Integer[] {1, 2, 3};
Integer[] orderedResult = sorter.sort(ordered);
assertSame(ordered, orderedResult);
assertArrayEquals(new Integer[] {1, 2, 3}, orderedResult);

// Fixture: reversed [3, 2, 1] -> [1, 2, 3]
Integer[] reversed = new Integer[] {3, 2, 1};
Integer[] reversedResult = sorter.sort(reversed);
assertSame(reversed, reversedResult);
assertArrayEquals(new Integer[] {1, 2, 3}, reversedResult);

// List overload from SortAlgorithm default interface
List<Integer> listResult = sorter.sort(Arrays.asList(3, 1, 2));
assertEquals(List.of(1, 2, 3), listResult);

System.out.println("CASE|smallest_empty|input=[]|expected=[]|actual=" + Arrays.toString(emptyResult));
System.out.println("CASE|smallest_single|input=[1]|expected=[1]|actual=" + Arrays.toString(singleResult));
System.out.println("CASE|mixed|input=[3, 1, 2]|expected=[1, 2, 3]|actual=" + Arrays.toString(mixedResult));
System.out.println("CASE|duplicates|input=[2, 2, 1]|expected=[1, 2, 2]|actual=" + Arrays.toString(duplicatesResult));
System.out.println("CASE|already_ordered|input=[1, 2, 3]|expected=[1, 2, 3]|actual=" + Arrays.toString(orderedResult));
System.out.println("CASE|reversed|input=[3, 2, 1]|expected=[1, 2, 3]|actual=" + Arrays.toString(reversedResult));
System.out.println("CASE|list_overload|input=[3, 1, 2]|expected=[1, 2, 3]|actual=" + listResult);
}
}
10 changes: 10 additions & 0 deletions work/R45-T036/before_refactor.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
# R45-T036 StrandSort Focused Refactoring Comparisons
# Source: src/main/java/com/thealgorithms/sorts/StrandSort.java
# Extracted responsibility: extractStrand(List<T>) isolates pulling the next non-decreasing strand from the remaining unsorted list.
CASE|smallest_empty|input=[]|expected=[]|actual=[]
CASE|smallest_single|input=[1]|expected=[1]|actual=[1]
CASE|mixed|input=[3, 1, 2]|expected=[1, 2, 3]|actual=[1, 2, 3]
CASE|duplicates|input=[2, 2, 1]|expected=[1, 2, 2]|actual=[1, 2, 2]
CASE|already_ordered|input=[1, 2, 3]|expected=[1, 2, 3]|actual=[1, 2, 3]
CASE|reversed|input=[3, 2, 1]|expected=[1, 2, 3]|actual=[1, 2, 3]
CASE|list_overload|input=[3, 1, 2]|expected=[1, 2, 3]|actual=[1, 2, 3]
96 changes: 96 additions & 0 deletions work/R45-T036/check.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
#!/usr/bin/env python3
"""Focused verification runner for R45-T036 (StrandSort focused refactoring)."""

from __future__ import annotations

import os
import pathlib
import re
import subprocess
import sys

REPO_ROOT = pathlib.Path(__file__).resolve().parents[2]
WORK_DIR = pathlib.Path(__file__).resolve().parent
TEST_CLASS = "com.thealgorithms.sorts.StrandSortTest"


def build_env() -> dict[str, str]:
env = os.environ.copy()
jdk21 = pathlib.Path("/opt/homebrew/opt/openjdk@21/libexec/openjdk.jdk/Contents/Home")
if "JAVA_HOME" not in env and jdk21.exists():
env["JAVA_HOME"] = str(jdk21)
env["PATH"] = f"{jdk21 / 'bin'}:{env.get('PATH', '')}"
return env


def capture_version(cmd: list[str], env: dict[str, str]) -> str:
proc = subprocess.run(cmd, capture_output=True, text=True, env=env)
combined = (proc.stdout + "\n" + proc.stderr).strip()
return combined.splitlines()[0] if combined else f"exit={proc.returncode}"


def main() -> int:
env = build_env()
WORK_DIR.mkdir(parents=True, exist_ok=True)

tool_versions = [
f"python3: {sys.version.splitlines()[0]}",
f"java: {capture_version(['java', '-version'], env)}",
f"mvn: {capture_version(['mvn', '-version'], env)}",
]
(WORK_DIR / "tool_versions.txt").write_text("\n".join(tool_versions) + "\n", encoding="utf-8")

cmd = [
"mvn",
"-B",
"test",
f"-Dtest={TEST_CLASS}",
"-Dsurefire.failIfNoSpecifiedTests=false",
]
proc = subprocess.run(cmd, cwd=REPO_ROOT, env=env, capture_output=True, text=True)
full_output = proc.stdout + ("\n" + proc.stderr if proc.stderr else "")
(WORK_DIR / "mvn_output.txt").write_text(full_output, encoding="utf-8")

summary_match = re.findall(
r"Tests run:\s*(\d+),\s*Failures:\s*(\d+),\s*Errors:\s*(\d+),\s*Skipped:\s*(\d+)",
full_output,
)
if summary_match:
tests_run, failures, errors, skipped = map(int, summary_match[-1])
else:
tests_run, failures, errors, skipped = 0, 0, 1, 0

case_lines = [line.strip() for line in full_output.splitlines() if line.strip().startswith("CASE|")]
(WORK_DIR / "comparisons.txt").write_text(
"\n".join(
[
"# R45-T036 StrandSort Focused Refactoring Comparisons",
"# Source: src/main/java/com/thealgorithms/sorts/StrandSort.java",
"# Extracted responsibility: extractStrand(List<T>) isolates pulling the next non-decreasing strand from the remaining unsorted list.",
*case_lines,
]
)
+ "\n",
encoding="utf-8",
)

passed = proc.returncode == 0 and tests_run > 0 and failures == 0 and errors == 0 and len(case_lines) >= 7
status = "PASS" if passed else "FAIL"
summary = (
f"task=R45-T036\n"
f"status={status}\n"
f"command={' '.join(cmd)}\n"
f"mvn_exit={proc.returncode}\n"
f"tests_run={tests_run}\n"
f"failures={failures}\n"
f"errors={errors}\n"
f"skipped={skipped}\n"
f"comparison_records={len(case_lines)}\n"
)
(WORK_DIR / "result.txt").write_text(summary, encoding="utf-8")
print(summary, end="")
return 0 if passed else 1


if __name__ == "__main__":
raise SystemExit(main())
10 changes: 10 additions & 0 deletions work/R45-T036/comparisons.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
# R45-T036 StrandSort Focused Refactoring Comparisons
# Source: src/main/java/com/thealgorithms/sorts/StrandSort.java
# Extracted responsibility: extractStrand(List<T>) isolates pulling the next non-decreasing strand from the remaining unsorted list.
CASE|smallest_empty|input=[]|expected=[]|actual=[]
CASE|smallest_single|input=[1]|expected=[1]|actual=[1]
CASE|mixed|input=[3, 1, 2]|expected=[1, 2, 3]|actual=[1, 2, 3]
CASE|duplicates|input=[2, 2, 1]|expected=[1, 2, 2]|actual=[1, 2, 2]
CASE|already_ordered|input=[1, 2, 3]|expected=[1, 2, 3]|actual=[1, 2, 3]
CASE|reversed|input=[3, 2, 1]|expected=[1, 2, 3]|actual=[1, 2, 3]
CASE|list_overload|input=[3, 1, 2]|expected=[1, 2, 3]|actual=[1, 2, 3]
60 changes: 60 additions & 0 deletions work/R45-T036/mvn_output.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
[INFO] Scanning for projects...
[INFO] Loaded 24540 auto-discovered prefixes for remote repository central (prefixes-central.txt)
[INFO]
[INFO] -----------------------< com.thealgorithms:Java >-----------------------
[INFO] Building Java 1.0-SNAPSHOT
[INFO] from pom.xml
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- jacoco:0.8.16:prepare-agent (default) @ Java ---
[INFO] argLine set to -javaagent:/Users/yuraj/.m2/repository/org/jacoco/org.jacoco.agent/0.8.16/org.jacoco.agent-0.8.16-runtime.jar=destfile=/Users/yuraj/.gemini/antigravity/scratch/TheAlgorithms-Java/target/jacoco.exec
[INFO]
[INFO] --- resources:3.5.0:resources (default-resources) @ Java ---
[INFO] skip non existing resourceDirectory /Users/yuraj/.gemini/antigravity/scratch/TheAlgorithms-Java/src/main/resources
[INFO]
[INFO] --- compiler:3.16.0:compile (default-compile) @ Java ---
[INFO] Recompiling the module because of changed source code.
[INFO] Compiling 848 source files with javac [debug release 21] to target/classes
[INFO]
[INFO] --- resources:3.5.0:testResources (default-testResources) @ Java ---
[INFO] skip non existing resourceDirectory /Users/yuraj/.gemini/antigravity/scratch/TheAlgorithms-Java/src/test/resources
[INFO]
[INFO] --- compiler:3.16.0:testCompile (default-testCompile) @ Java ---
[INFO] Recompiling the module because of changed dependency.
[INFO] Compiling 796 source files with javac [debug release 21] to target/test-classes
[INFO]
[INFO] --- surefire:3.6.0:test (default-test) @ Java ---
[INFO] Using auto detected provider org.apache.maven.surefire.junitplatform.JUnitPlatformProvider
[INFO]
[INFO] -------------------------------------------------------
[INFO] T E S T S
[INFO] -------------------------------------------------------
[INFO] Running com.thealgorithms.sorts.StrandSortTest
CASE|smallest_empty|input=[]|expected=[]|actual=[]
CASE|smallest_single|input=[1]|expected=[1]|actual=[1]
CASE|mixed|input=[3, 1, 2]|expected=[1, 2, 3]|actual=[1, 2, 3]
CASE|duplicates|input=[2, 2, 1]|expected=[1, 2, 2]|actual=[1, 2, 2]
CASE|already_ordered|input=[1, 2, 3]|expected=[1, 2, 3]|actual=[1, 2, 3]
CASE|reversed|input=[3, 2, 1]|expected=[1, 2, 3]|actual=[1, 2, 3]
CASE|list_overload|input=[3, 1, 2]|expected=[1, 2, 3]|actual=[1, 2, 3]
[INFO] Tests run: 39, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.154 s -- in com.thealgorithms.sorts.StrandSortTest
[INFO]
[INFO] Results:
[INFO]
[INFO] Tests run: 39, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO]
[INFO] --- jacoco:0.8.16:report (generate-code-coverage-report) @ Java ---
[INFO] Loading execution data file /Users/yuraj/.gemini/antigravity/scratch/TheAlgorithms-Java/target/jacoco.exec
[INFO] Analyzed bundle 'Java' with 1073 classes
[WARNING] Classes in bundle 'Java' do not match with execution data. For report generation the same class files must be used as at runtime.
[WARNING] Execution data for class com/thealgorithms/maths/FindMinRecursion does not match.
[WARNING] Execution data for class com/thealgorithms/matrix/matrixexponentiation/Fibonacci does not match.
[WARNING] Execution data for class com/thealgorithms/backtracking/Combination does not match.
[WARNING] Execution data for class com/thealgorithms/matrix/LUDecomposition does not match.
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 9.444 s
[INFO] Finished at: 2026-11-18T22:42:35+05:30
[INFO] ------------------------------------------------------------------------
9 changes: 9 additions & 0 deletions work/R45-T036/result.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
task=R45-T036
status=PASS
command=mvn -B test -Dtest=com.thealgorithms.sorts.StrandSortTest -Dsurefire.failIfNoSpecifiedTests=false
mvn_exit=0
tests_run=39
failures=0
errors=0
skipped=0
comparison_records=7
3 changes: 3 additions & 0 deletions work/R45-T036/tool_versions.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
python3: 3.15.2 (main, Oct 25 2026, 16:57:51) [Clang 21.0.0 (clang-2100.3.34.2)]
java: openjdk version "21.0.13.1" 2026-11-17
mvn: Apache Maven 3.10.1 (3afd8084b5629f80b97750906a719879ed4cd283)