Added PancakeSort and the other minor changes
This commit is contained in:
parent
e15cfb29b1
commit
e83317fd89
@ -10,7 +10,7 @@ import static sort.SortUtils.*;
|
|||||||
* Heap Sort Algorithm
|
* Heap Sort Algorithm
|
||||||
* Implements MinHeap
|
* Implements MinHeap
|
||||||
*
|
*
|
||||||
* @author Unknown
|
* @author Podshivalov Nikita (https://github.com/nikitap492)
|
||||||
*
|
*
|
||||||
*/
|
*/
|
||||||
public class HeapSort implements SortAlgorithm {
|
public class HeapSort implements SortAlgorithm {
|
||||||
|
47
Sorts/src/sort/PancakeSort.java
Normal file
47
Sorts/src/sort/PancakeSort.java
Normal 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);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
}
|
@ -56,6 +56,20 @@ final class SortUtils {
|
|||||||
* @param toPrint - the array which should be printed
|
* @param toPrint - the array which should be printed
|
||||||
*/
|
*/
|
||||||
static void print(Object[] toPrint){
|
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--);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user