diff --git a/Sorts/src/sort/HeapSort.java b/Sorts/src/sort/HeapSort.java index 1d009dcf1..6fab3747f 100644 --- a/Sorts/src/sort/HeapSort.java +++ b/Sorts/src/sort/HeapSort.java @@ -9,8 +9,8 @@ import static sort.SortUtils.*; /** * Heap Sort Algorithm * Implements MinHeap - * - * @author Unknown + * + * @author Podshivalov Nikita (https://github.com/nikitap492) * */ public class HeapSort implements SortAlgorithm { diff --git a/Sorts/src/sort/PancakeSort.java b/Sorts/src/sort/PancakeSort.java new file mode 100644 index 000000000..902db4b39 --- /dev/null +++ b/Sorts/src/sort/PancakeSort.java @@ -0,0 +1,47 @@ +package sort; + +import static sort.SortUtils.*; + +/** + * Implementation of gnome sort + * + * @author Podshivalov Nikita (https://github.com/nikitap492) + * @since 2018-04-10 + * + **/ +public class PancakeSort implements SortAlgorithm { + + + @Override + public > T[] sort(T[] array){ + int size = array.length; + + for (int i = 0; i < size; i++) { + T max = array[0]; + int index = 0; + for (int j = 0; j < size - i; j++) { + if ( less(max, array[j]) ) { + max = array[j]; + index = j; + } + } + flip(array, index, array.length - 1 - i); + } + return array; + } + + + public static void main(String[] args) { + + Integer[] arr = {10, 9, 8, 7, 6, 15, 14, 7, 4, 3, 8, 6, 3, 1 ,2, -2, -5, -8, -3, -1, 13, 12, 11, 5, 4, 3, 2, 1}; + PancakeSort pancakeSort = new PancakeSort(); + System.out.println("After sorting:"); + pancakeSort.sort(arr); + print(arr); + } + + + + + +} diff --git a/Sorts/src/sort/SortUtils.java b/Sorts/src/sort/SortUtils.java index e1cf8482d..8766e9d0e 100644 --- a/Sorts/src/sort/SortUtils.java +++ b/Sorts/src/sort/SortUtils.java @@ -56,6 +56,20 @@ final class SortUtils { * @param toPrint - the array which should be printed */ static void print(Object[] toPrint){ - print(Arrays.asList(toPrint)); + System.out.println(Arrays.toString(toPrint)); + } + + + + /** + * Swaps all position from {@param left} to @{@param right} for {@param array} + * @param array is an array + * @param left is a left flip border of the array + * @param right is a right flip border of the array + */ + static > void flip(T[] array, int left, int right) { + while (left <= right) { + swap(array, left++ , right--); + } } }