Added PancakeSort and the other minor changes

This commit is contained in:
nik 2018-04-10 12:48:21 +03:00
parent e15cfb29b1
commit e83317fd89
3 changed files with 64 additions and 3 deletions

View File

@ -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 {

View File

@ -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 extends Comparable<T>> 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);
}
}

View File

@ -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 <T extends Comparable<T>> void flip(T[] array, int left, int right) {
while (left <= right) {
swap(array, left++ , right--);
}
}
}