BAEL-6225 Refactor code and move package. (#14132)

* BAEL-6225 Refactor code and move package.

* BAEL-6225 Move code to core-java-lang-oop-patterns.

* BAEL-6225 Refactor test name.

* BAEL-6225 Refactor test name.

* BAEL-6225 Update with singleton instances.
This commit is contained in:
Vali Tuguran 2023-07-24 10:47:07 +03:00 committed by GitHub
parent 4291c56bdb
commit 526e9845a8
4 changed files with 91 additions and 0 deletions

View File

@ -0,0 +1,20 @@
package com.baeldung.stateless;
public enum BubbleSort implements SortingStrategy {
INSTANCE;
@Override
public void sort(int[] array) {
int n = array.length;
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (array[j] > array[j + 1]) {
int swap = array[j];
array[j] = array[j + 1];
array[j + 1] = swap;
}
}
}
}
}

View File

@ -0,0 +1,36 @@
package com.baeldung.stateless;
public enum QuickSort implements SortingStrategy {
INSTANCE;
@Override
public void sort(int[] array) {
quickSort(array, 0, array.length - 1);
}
private void quickSort(int[] array, int begin, int end) {
if (begin < end) {
int pi = partition(array, begin, end);
quickSort(array, begin, pi - 1);
quickSort(array, pi + 1, end);
}
}
private int partition(int[] array, int low, int high) {
int pivot = array[high];
int i = low - 1;
for (int j = low; j < high; j++) {
if (array[j] < pivot) {
i++;
int swap = array[i];
array[i] = array[j];
array[j] = swap;
}
}
int swap = array[i + 1];
array[i + 1] = array[high];
array[high] = swap;
return i + 1;
}
}

View File

@ -0,0 +1,7 @@
package com.baeldung.stateless;
public interface SortingStrategy {
public void sort(int[] array);
}

View File

@ -0,0 +1,28 @@
package com.baeldung.stateless;
import static org.junit.Assert.assertArrayEquals;
import org.junit.jupiter.api.Test;
public class ArraySortingUnitTest {
@Test
void givenArray_whenBubbleSorting_thenSorted() {
int[] arrayToSort = {17, 6, 11, 41, 5, 3, 4, -9};
int[] sortedArray = {-9, 3, 4, 5, 6, 11, 17, 41};
SortingStrategy sortingStrategy = BubbleSort.INSTANCE;
sortingStrategy.sort(arrayToSort);
assertArrayEquals(sortedArray, arrayToSort);
}
@Test
void givenArray_whenQuickSortSorting_thenSorted() {
int[] arrayToSort = {17, 6, 11, 41, 5, 3, 4, -9};
int[] sortedArray = {-9, 3, 4, 5, 6, 11, 17, 41};
SortingStrategy sortingStrategy = QuickSort.INSTANCE;
sortingStrategy.sort(arrayToSort);
assertArrayEquals(sortedArray, arrayToSort);
}
}