2018-11-14 01:15:47 +08:00
|
|
|
package Sorts;
|
2018-04-09 17:05:41 +08:00
|
|
|
|
|
|
|
import java.util.Arrays;
|
|
|
|
import java.util.List;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* The class contains util methods
|
|
|
|
*
|
|
|
|
* @author Podshivalov Nikita (https://github.com/nikitap492)
|
|
|
|
**/
|
|
|
|
final class SortUtils {
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Helper method for swapping places in array
|
2019-05-09 19:32:54 +08:00
|
|
|
*
|
2018-04-09 17:05:41 +08:00
|
|
|
* @param array The array which elements we want to swap
|
2019-05-09 19:32:54 +08:00
|
|
|
* @param idx index of the first element
|
|
|
|
* @param idy index of the second element
|
2018-04-09 17:05:41 +08:00
|
|
|
*/
|
2019-05-09 19:32:54 +08:00
|
|
|
static <T> boolean swap(T[] array, int idx, int idy) {
|
2018-04-09 17:05:41 +08:00
|
|
|
T swap = array[idx];
|
|
|
|
array[idx] = array[idy];
|
|
|
|
array[idy] = swap;
|
2018-04-09 20:48:08 +08:00
|
|
|
return true;
|
2018-04-09 17:05:41 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
* This method checks if first element is less then the other element
|
2019-05-09 19:32:54 +08:00
|
|
|
*
|
2018-04-09 17:05:41 +08:00
|
|
|
* @param v first element
|
|
|
|
* @param w second element
|
|
|
|
* @return true if the first element is less then the second element
|
|
|
|
*/
|
|
|
|
static <T extends Comparable<T>> boolean less(T v, T w) {
|
|
|
|
return v.compareTo(w) < 0;
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Just print list
|
2019-05-09 19:32:54 +08:00
|
|
|
*
|
2018-04-09 17:05:41 +08:00
|
|
|
* @param toPrint - a list which should be printed
|
|
|
|
*/
|
2019-05-09 19:32:54 +08:00
|
|
|
static void print(List<?> toPrint) {
|
2018-04-09 17:05:41 +08:00
|
|
|
toPrint.stream()
|
|
|
|
.map(Object::toString)
|
|
|
|
.map(str -> str + " ")
|
|
|
|
.forEach(System.out::print);
|
|
|
|
|
|
|
|
System.out.println();
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Prints an array
|
2019-05-09 19:32:54 +08:00
|
|
|
*
|
2018-04-09 17:05:41 +08:00
|
|
|
* @param toPrint - the array which should be printed
|
|
|
|
*/
|
2019-05-09 19:32:54 +08:00
|
|
|
static void print(Object[] toPrint) {
|
2018-04-10 17:48:21 +08:00
|
|
|
System.out.println(Arrays.toString(toPrint));
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Swaps all position from {@param left} to @{@param right} for {@param array}
|
2019-05-09 19:32:54 +08:00
|
|
|
*
|
2018-04-10 17:48:21 +08:00
|
|
|
* @param array is an array
|
2019-05-09 19:32:54 +08:00
|
|
|
* @param left is a left flip border of the array
|
2018-04-10 17:48:21 +08:00
|
|
|
* @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) {
|
2019-05-09 19:32:54 +08:00
|
|
|
swap(array, left++, right--);
|
2018-04-10 17:48:21 +08:00
|
|
|
}
|
2018-04-09 17:05:41 +08:00
|
|
|
}
|
|
|
|
}
|