Skip to content

Commit

Permalink
Comb sort was implemented
Browse files Browse the repository at this point in the history
  • Loading branch information
nikitap492 committed Apr 12, 2018
1 parent f808a2b commit cf77867
Show file tree
Hide file tree
Showing 3 changed files with 86 additions and 62 deletions.
62 changes: 0 additions & 62 deletions Sorts/CombSort.java

This file was deleted.

76 changes: 76 additions & 0 deletions Sorts/src/sort/CombSort.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
package sort;

import static sort.SortUtils.*;


/**
*
* Comb Sort algorithm implementation
*
* Best-case performance O(n * log(n))
* Worst-case performance O(n ^ 2)
* Worst-case space complexity O(1)
*
* Comb sort improves on bubble sort.
*
*
* @see BubbleSort
* @see SortAlgorithm
*
* @author Sandeep Roy (https://github.com/sandeeproy99)
* @author Podshivalov Nikita (https://github.com/nikitap492)
*
*/
class CombSort implements SortAlgorithm {

// To find gap between elements
private int nextGap(int gap) {
// Shrink gap by Shrink factor
gap = ( gap * 10 ) / 13;
return ( gap < 1 ) ? 1 : gap;
}

/**
* 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;

// initialize gap
int gap = size;

// Initialize swapped as true to make sure that loop runs
boolean swapped = true;

// Keep running while gap is more than 1 and last iteration caused a swap
while (gap != 1 || swapped) {
// Find next gap
gap = nextGap(gap);

// Initialize swapped as false so that we can check if swap happened or not
swapped = false;

// 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);
}
}
}
return arr;
}

// 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);

System.out.println("sorted array");
print(arr);
}
}
10 changes: 10 additions & 0 deletions Sorts/src/sort/SortAlgorithm.java
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,18 @@
**/
public interface SortAlgorithm {

/**
* Main method arrays sorting algorithms
* @param unsorted - an array should be sorted
* @return a sorted array
*/
<T extends Comparable<T>> T[] sort(T[] unsorted);

/**
* Auxiliary method for algorithms what wanted to work with lists from JCF
* @param unsorted - a list should be sorted
* @return a sorted list
*/
@SuppressWarnings("unchecked")
default <T extends Comparable<T>> List<T> sort(List<T> unsorted){
return Arrays.asList(sort(unsorted.toArray((T[]) new Comparable[unsorted.size()])));
Expand Down

0 comments on commit cf77867

Please sign in to comment.