JavaAlgorithms/Sorts/CombSort.java

72 lines
1.7 KiB
Java
Raw Normal View History

2018-11-14 01:15:47 +08:00
package Sorts;
2018-04-12 15:14:22 +08:00
2018-11-14 01:15:47 +08:00
import static Sorts.SortUtils.*;
2018-04-12 15:14:22 +08:00
/**
* Comb Sort algorithm implementation
2020-10-24 18:23:28 +08:00
*
* <p>Best-case performance O(n * log(n)) Worst-case performance O(n ^ 2) Worst-case space
* complexity O(1)
*
* <p>Comb sort improves on bubble sort.
2018-04-12 15:14:22 +08:00
*
* @author Sandeep Roy (https://github.com/sandeeproy99)
* @author Podshivalov Nikita (https://github.com/nikitap492)
* @see BubbleSort
* @see SortAlgorithm
2018-04-12 15:14:22 +08:00
*/
class CombSort implements SortAlgorithm {
2020-10-24 18:23:28 +08:00
// To find gap between elements
private int nextGap(int gap) {
// Shrink gap by Shrink factor
gap = (gap * 10) / 13;
return (gap < 1) ? 1 : gap;
}
2018-04-12 15:14:22 +08:00
2020-10-24 18:23:28 +08:00
/**
* Function to sort arr[] using Comb
*
* @param arr - an array should be sorted
* @return sorted array
*/
@Override
public <T extends Comparable<T>> T[] sort(T[] arr) {
int size = arr.length;
2018-04-12 15:14:22 +08:00
2020-10-24 18:23:28 +08:00
// initialize gap
int gap = size;
2020-10-24 18:23:28 +08:00
// Initialize swapped as true to make sure that loop runs
boolean swapped = true;
2020-10-24 18:23:28 +08:00
// Keep running while gap is more than 1 and last iteration caused a swap
while (gap != 1 || swapped) {
// Find next gap
gap = nextGap(gap);
2020-10-24 18:23:28 +08:00
// Initialize swapped as false so that we can check if swap happened or not
swapped = false;
2020-10-24 18:23:28 +08:00
// Compare all elements with current gap
for (int i = 0; i < size - gap; i++) {
if (less(arr[i + gap], arr[i])) {
// Swap arr[i] and arr[i+gap]
swapped = swap(arr, i, i + gap);
2018-04-12 15:14:22 +08:00
}
2020-10-24 18:23:28 +08:00
}
2018-04-12 15:14:22 +08:00
}
2020-10-24 18:23:28 +08:00
return arr;
}
2020-10-24 18:23:28 +08:00
// Driver method
public static void main(String[] args) {
CombSort ob = new CombSort();
Integer[] arr = {8, 4, 1, 56, 3, -44, -1, 0, 36, 34, 8, 12, -66, -78, 23, -6, 28, 0};
ob.sort(arr);
2020-10-24 18:23:28 +08:00
System.out.println("sorted array");
print(arr);
}
2018-04-12 15:14:22 +08:00
}