Skip to content
Closed
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
39 changes: 39 additions & 0 deletions src/main/java/com/thealgorithms/sorts/StalinSort.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package com.thealgorithms.sorts;

/**
* Stalin Sort is a sorting algorithm that works by iterating through the array and
* maintaining a sorted portion of the array at the beginning. If a number is encountered
* that is smaller than the last number in the sorted portion, it is discarded (not added).
* This algorithm is not stable and will not sort all elements correctly if there are
* elements that violate the sort order.
*
* For more information, see:
* https://en.wikipedia.org/wiki/Stalin_sort
*/
public class StalinSort implements SortAlgorithm {

@Override
public <T extends Comparable<T>> T[] sort(T[] array) {
if (array.length == 0) {
Copy link
Contributor

@saahil-mahato saahil-mahato Oct 11, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

add null check here to prevent null pointer exception.

return array;
}

T[] result = (T[]) new Comparable[array.length];
int index = 0;
result[index++] = array[0];

for (int i = 1; i < array.length; i++) {
if (SortUtils.less(result[index - 1], array[i])) {
result[index++] = array[i];
}
}

return trimArray(result, index);
}

private <T> T[] trimArray(T[] array, int length) {
Copy link
Contributor

@saahil-mahato saahil-mahato Oct 11, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This just adds unnecessary overhead. We can remove this if we use ArrayList.

List<T> result = new ArrayList<>();
result.add(array[0]); 

for (int i = 1; i < array.length; i++) {
    if (SortUtils.less(result.get(result.size() - 1), array[i])) {
        result.add(array[i]);
    }
}

T[] trimmedArray = (T[]) new Comparable[length];
System.arraycopy(array, 0, trimmedArray, 0, length);
return trimmedArray;
}
}
Loading