Merge pull request #415 from nikitap492/search

Added documentation to the searching algorithms and refactored them
This commit is contained in:
Christian Bender 2018-04-13 00:35:34 +02:00 committed by GitHub
commit f1cc15b6a8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
16 changed files with 610 additions and 480 deletions

View File

@ -1,71 +0,0 @@
import java.util.Scanner;
/**
*
* @author Varun Upadhyay (https://github.com/varunu28)
*
*/
class BinarySearch
{
/**
* This method implements the Generic Binary Search
*
* @param array The array to make the binary search
* @param key The number you are looking for
* @param lb The lower bound
* @param ub The upper bound
* @return the location of the key
**/
public static <T extends Comparable<T>> int BS(T array[], T key, int lb, int ub)
{
if ( lb > ub)
return -1;
int mid = (ub+lb) >>> 1;
int comp = key.compareTo(array[mid]);
if (comp < 0)
return (BS(array, key, lb, mid-1));
if (comp > 0)
return (BS(array, key, mid + 1, ub));
return mid;
}
// Driver Program
public static void main(String[] args)
{
Scanner input=new Scanner(System.in);
// For INTEGER Input
Integer[] array = new Integer[10];
int key = 5;
for (int i = 0; i < 10 ; i++ )
array[i] = i+1;
int index = BS(array, key, 0, 9);
if (index != -1)
System.out.println("Number " + key + " found at index number : " + index);
else
System.out.println("Not found");
// For STRING Input
String[] array1 = {"a", "b", "c", "d", "e"};
String key1 = "d";
int index1 = BS(array1, key1, 0, array1.length-1);
if (index1 != -1)
System.out.println("String " + key1 + " found at index number : " + index1);
else
System.out.println("Not found");
input.close();
}
}

View File

@ -1,59 +0,0 @@
import java.util.Arrays;
import java.util.Random;
/**
*
* @author Gabriele La Greca : https://github.com/thegabriele97
*
*/
public final class IterativeBinarySearch {
/**
* This method implements an iterative version of binary search algorithm
*
* @param array a sorted array
* @param key the key to search in array
*
* @return the index of key in the array or -1 if not found
*/
public static <T extends Comparable<T>> int binarySearch(T[] array, T key) {
int l, r, k, cmp;
l = 0;
r = array.length - 1;
while (l <= r) {
k = (l + r) / 2;
cmp = key.compareTo(array[k]);
if (cmp == 0) {
return k;
} else if (cmp < 0) {
r = --k;
} else if (cmp > 0) {
l = ++k;
}
}
return -1;
}
//Only a main method for test purpose
public static void main(String[] args) {
Random rand = new Random();
int base = rand.nextInt(1000);
Integer[] array = new Integer[65535];
for (int i = 0; i < array.length; i++) {
array[i] = base + (i + 1);
}
//Arrays.sort(array); //if needed
Integer key = base + rand.nextInt(array.length * 2); //can generate keys that aren't in array
System.out.println(binarySearch(array, key));
System.out.println(Arrays.binarySearch(array, key));
}
}

View File

@ -1,77 +0,0 @@
import java.io.BufferedReader;
import java.io.InputStreamReader;
/**
*
* @author Varun Upadhyay (https://github.com/varunu28)
*
*/
public class LinearSearch{
/**
* The main method
* @param args Command line arguments
*/
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
// Test for Integer inputs
Integer[] myArray;
int size = 0;
//Prompt user to create array and its elements
System.out.print("Enter the array size: ");
size = Integer.parseInt(br.readLine());
myArray = new Integer[size];
for (int i = 0; i < size; i++){
System.out.print("For index " + i + ", enter an integer: ");
myArray[i] = Integer.parseInt(br.readLine());
}
//Prompt user to search for particular element
System.out.print("Enter integer to search for: ");
Integer key = Integer.parseInt(br.readLine());
//Output array and index of target element, if found
System.out.printf("The integer %d is found in index %d\n", key, linearSearch(myArray, key));
// Test for String inputs
String[] myArray1;
int size1 = 0;
//Prompt user to create array and its elements
System.out.print("Enter the array size: ");
size1 = Integer.parseInt(br.readLine());
myArray1 = new String[size];
for (int i = 0; i < size1; i++){
System.out.print("For index " + i + ", enter a String: ");
myArray1[i] = br.readLine();
}
//Prompt user to search for particular element
System.out.print("Enter String to search for: ");
String key1 = br.readLine();
//Output array and index of target element, if found
System.out.printf("The string %s is found in index %d\n", key1, linearSearch(myArray1, key1));
}
/**
* Generic Linear search method
*
* @param array List to be searched
* @param value Key being searched for
* @return Location of the key
*/
public static <T extends Comparable<T>> int linearSearch(T[] array, T value) {
int lo = 0;
int hi = array.length - 1;
for (int i = lo; i <= hi; i++) {
if (array[i].compareTo(value) == 0) {
return i;
}
}
return -1;
}
}

View File

@ -1,84 +0,0 @@
import java.util.*;
/**
* Program to perform Saddleback Search
* Given a sorted 2D array(elements are sorted across every row and column, assuming ascending order)
* of size n*m we can search a given element in O(n+m)
*
* we start from bottom left corner
* if the current element is greater than the given element then we move up
* else we move right
* Sample Input:
* 5 5 ->Dimensions
* -10 -5 -3 4 9
* -6 -2 0 5 10
* -4 -1 1 6 12
* 2 3 7 8 13
* 100 120 130 140 150
* 140 ->element to be searched
* output: 4 3 // first value is row, second one is column
*
* @author Nishita Aggarwal
*
*/
public class SaddlebackSearch {
/**
* This method performs Saddleback Search
*
* @param arr The **Sorted** array in which we will search the element.
* @param crow the current row.
* @param ccol the current column.
* @param ele the element that we want to search for.
*
* @return The index(row and column) of the element if found.
* Else returns -1 -1.
*/
static int[] search(int arr[][],int crow,int ccol,int ele){
//array to store the answer row and column
int ans[]={-1,-1};
if(crow<0 || ccol>=arr[crow].length){
return ans;
}
if(arr[crow][ccol]==ele)
{
ans[0]=crow;
ans[1]=ccol;
return ans;
}
//if the current element is greater than the given element then we move up
else if(arr[crow][ccol]>ele)
{
return search(arr,crow-1,ccol,ele);
}
//else we move right
return search(arr,crow,ccol+1,ele);
}
/**
* Main method
*
* @param args Command line arguments
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc=new Scanner(System.in);
int arr[][];
int i,j,rows=sc.nextInt(),col=sc.nextInt();
arr=new int[rows][col];
for(i=0;i<rows;i++)
{
for(j=0;j<col;j++){
arr[i][j]=sc.nextInt();
}
}
int ele=sc.nextInt();
//we start from bottom left corner
int ans[]=search(arr,rows-1,0,ele);
System.out.println(ans[0]+" "+ans[1]);
sc.close();
}
}

View File

@ -1,74 +0,0 @@
import java.util.Scanner;
public class TernarySearch{
/**
* @param arr The **Sorted** array in which we will search the element.
* @param value The value that we want to search for.
* @return The index of the element if found.
* Else returns -1.
*/
public static int ternarySearch(int[] arr, int value){
return ternarySearch(arr, value, 0, arr.length - 1);
}
/**
* @param arr The **Sorted** array in which we will search the element.
* @param key The value that we want to search for.
* @param start The starting index from which we will start Searching.
* @param end The ending index till which we will Search.
* @return Returns the index of the Element if found.
* Else returns -1.
*/
public static int ternarySearch(int[] arr, int key, int start, int end) {
if (start > end){
return -1;
}
/* First boundary: add 1/3 of length to start */
int mid1 = start + (end - start) / 3;
/* Second boundary: add 2/3 of length to start */
int mid2 = start + 2 * (end - start) / 3;
if (arr[mid1] == key) {
return mid1;
}
else if (arr[mid2] == key) {
return mid2;
}
/* Search the first (1/3) rd part of the array.*/
else if (key < arr[mid1]) {
return ternarySearch(arr, key, start, mid1 - 1);
}
/* Search 3rd (1/3)rd part of the array */
else if (key > arr[mid2]) {
return ternarySearch(arr, key, mid2 + 1, end);
}
/* Search middle (1/3)rd part of the array */
else {
return ternarySearch(arr, key, mid1, mid2);
}
}
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Enter number of elements in the array");
int n = s.nextInt();
int arr[] = new int[n];
System.out.println("Enter the elements of the Sorted array");
for (int i= 0; i < n; i++){
arr[i] = s.nextInt();
}
System.out.println("Enter element to search for : ");
int k = s.nextInt();
int ans = ternarySearch(arr, k);
if (ans == -1) {
System.out.println(" The element is not present in the array.");
}
else {
System.out.println("The element is present at the position " + (ans+1));
}
}
}

View File

@ -1,53 +0,0 @@
class Test
{
// Array of items on which search will
// be conducted.
static int arr[] = new int[]{10, 12, 13, 16, 18, 19, 20, 21, 22, 23,
24, 33, 35, 42, 47};
// If x is present in arr[0..n-1], then returns
// index of it, else returns -1.
static int interpolationSearch(int x)
{
// Find indexes of two corners
int lo = 0, hi = (arr.length - 1);
// Since array is sorted, an element present
// in array must be in range defined by corner
while (lo <= hi && x >= arr[lo] && x <= arr[hi])
{
// Probing the position with keeping
// uniform distribution in mind.
int pos = lo + (((hi-lo) /
(arr[hi]-arr[lo]))*(x - arr[lo]));
// Condition of target found
if (arr[pos] == x)
return pos;
// If x is larger, x is in upper part
if (arr[pos] < x)
lo = pos + 1;
// If x is smaller, x is in lower part
else
hi = pos - 1;
}
return -1;
}
// Driver method
public static void main(String[] args)
{
int x = 18; // Element to be searched
int index = interpolationSearch(x);
// If element was found
if (index != -1)
System.out.println("Element found at index " + index);
else
System.out.println("Element not found.");
}
}

View File

@ -0,0 +1,94 @@
package search;
import java.util.Arrays;
import java.util.Random;
import java.util.stream.Stream;
import static java.lang.String.format;
/**
*
*
*
* Binary search is one of the most popular algorithms
* The algorithm finds the position of a target value within a sorted array
*
* Worst-case performance O(log n)
* Best-case performance O(1)
* Average performance O(log n)
* Worst-case space complexity O(1)
*
*
* @author Varun Upadhyay (https://github.com/varunu28)
* @author Podshivalov Nikita (https://github.com/nikitap492)
*
* @see SearchAlgorithm
* @see IterativeBinarySearch
*
*/
class BinarySearch implements SearchAlgorithm {
/**
*
* @param array is an array where the element should be found
* @param key is an element which should be found
* @param <T> is any comparable type
* @return index of the element
*/
@Override
public <T extends Comparable<T>> int find(T array[], T key) {
return search(array, key, 0, array.length);
}
/**
* This method implements the Generic Binary Search
*
* @param array The array to make the binary search
* @param key The number you are looking for
* @param left The lower bound
* @param right The upper bound
* @return the location of the key
**/
private <T extends Comparable<T>> int search(T array[], T key, int left, int right){
if (right < left) return -1; // this means that the key not found
// find median
int median = (left + right) >>> 1;
int comp = key.compareTo(array[median]);
if (comp < 0) {
return search(array, key, left, median - 1);
}
if (comp > 0) {
return search(array, key, median + 1, right);
}
return median;
}
// Driver Program
public static void main(String[] args) {
//just generate data
Random r = new Random();
int size = 100;
int maxElement = 100000;
Integer[] integers = Stream.generate(() -> r.nextInt(maxElement)).limit(size).sorted().toArray(Integer[]::new);
//the element that should be found
Integer shouldBeFound = integers[r.nextInt(size - 1)];
BinarySearch search = new BinarySearch();
int atIndex = search.find(integers, shouldBeFound);
System.out.println(String.format("Should be found: %d. Found %d at index %d. An array length %d"
, shouldBeFound, integers[atIndex], atIndex, size));
int toCheck = Arrays.binarySearch(integers, shouldBeFound);
System.out.println(format("Found by system method at an index: %d. Is equal: %b", toCheck, toCheck == atIndex));
}
}

View File

@ -0,0 +1,79 @@
package search;
import java.util.Arrays;
import java.util.Random;
import java.util.stream.IntStream;
import static java.lang.String.format;
/**
*
* Interpolation search algorithm implementation
*
* Worst-case performance O(n)
* Best-case performance O(1)
* Average performance O(log(log(n))) if the elements are uniformly distributed if not O(n)
* Worst-case space complexity O(1)
*
*
* @author Podshivalov Nikita (https://github.com/nikitap492)
*
*/
class InterpolationSearch {
/**
* @param array is a sorted array
* @param key is a value what shoulb be found in the array
* @return an index if the array contains the key unless -1
*/
public int find(int array[], int key) {
// Find indexes of two corners
int start = 0, end = (array.length - 1);
// Since array is sorted, an element present
// in array must be in range defined by corner
while (start <= end && key >= array[start] && key <= array[end])
{
// Probing the position with keeping
// uniform distribution in mind.
int pos = start + (((end-start) / (array[end]-array[start]))*(key - array[start]));
// Condition of target found
if (array[pos] == key)
return pos;
// If key is larger, key is in upper part
if (array[pos] < key)
start = pos + 1;
// If key is smaller, x is in lower part
else
end = pos - 1;
}
return -1;
}
// Driver method
public static void main(String[] args) {
Random r = new Random();
int size = 100;
int maxElement = 100000;
int[] integers = IntStream.generate(() -> r.nextInt(maxElement)).limit(size).sorted().toArray();
//the element that should be found
Integer shouldBeFound = integers[r.nextInt(size - 1)];
InterpolationSearch search = new InterpolationSearch();
int atIndex = search.find(integers, shouldBeFound);
System.out.println(String.format("Should be found: %d. Found %d at index %d. An array length %d"
, shouldBeFound, integers[atIndex], atIndex, size));
int toCheck = Arrays.binarySearch(integers, shouldBeFound);
System.out.println(format("Found by system method at an index: %d. Is equal: %b", toCheck, toCheck == atIndex));
}
}

View File

@ -0,0 +1,82 @@
package search;
import java.util.Arrays;
import java.util.Random;
import java.util.stream.Stream;
import static java.lang.String.format;
/**
* Binary search is one of the most popular algorithms
* This class represents iterative version {@link BinarySearch}
* Iterative binary search is likely to have lower constant factors because it doesn't involve the overhead of manipulating the call stack.
* But in java the recursive version can be optimized by the compiler to this version.
*
* Worst-case performance O(log n)
* Best-case performance O(1)
* Average performance O(log n)
* Worst-case space complexity O(1)
*
* @author Gabriele La Greca : https://github.com/thegabriele97
* @author Podshivalov Nikita (https://github.com/nikitap492)
*
* @see SearchAlgorithm
* @see BinarySearch
*
*/
public final class IterativeBinarySearch implements SearchAlgorithm {
/**
* This method implements an iterative version of binary search algorithm
*
* @param array a sorted array
* @param key the key to search in array
*
* @return the index of key in the array or -1 if not found
*/
@Override
public <T extends Comparable<T>> int find(T[] array, T key) {
int l, r, k, cmp;
l = 0;
r = array.length - 1;
while (l <= r) {
k = (l + r) / 2;
cmp = key.compareTo(array[k]);
if (cmp == 0) {
return k;
} else if (cmp < 0) {
r = --k;
} else {
l = ++k;
}
}
return -1;
}
//Only a main method for test purpose
public static void main(String[] args) {
Random r = new Random();
int size = 100;
int maxElement = 100000;
Integer[] integers = Stream.generate(() -> r.nextInt(maxElement)).limit(size).sorted().toArray(Integer[]::new);
//the element that should be found
Integer shouldBeFound = integers[r.nextInt(size - 1)];
IterativeBinarySearch search = new IterativeBinarySearch();
int atIndex = search.find(integers, shouldBeFound);
System.out.println(String.format("Should be found: %d. Found %d at index %d. An array length %d"
, shouldBeFound, integers[atIndex], atIndex, size));
int toCheck = Arrays.binarySearch(integers, shouldBeFound);
System.out.println(format("Found by system method at an index: %d. Is equal: %b", toCheck, toCheck == atIndex));
}
}

View File

@ -0,0 +1,63 @@
package search;
import java.util.Random;
import java.util.stream.Stream;
/**
* Linear search is the easiest search algorithm
* It works with sorted and unsorted arrays (an binary search works only with sorted array)
* This algorithm just compares all elements of an array to find a value
*
* Worst-case performance O(n)
* Best-case performance O(1)
* Average performance O(n)
* Worst-case space complexity
*
*
* @author Varun Upadhyay (https://github.com/varunu28)
* @author Podshivalov Nikita (https://github.com/nikitap492)
*
*
* @see BinarySearch
* @see SearchAlgorithm
*/
public class LinearSearch implements SearchAlgorithm {
/**
* Generic Linear search method
*
* @param array List to be searched
* @param value Key being searched for
* @return Location of the key
*/
@Override
public <T extends Comparable<T>> int find(T[] array, T value) {
for (int i = 0; i < array.length ; i++) {
if (array[i].compareTo(value) == 0) {
return i;
}
}
return -1;
}
public static void main(String[] args) {
//just generate data
Random r = new Random();
int size = 200;
int maxElement = 100;
Integer[] integers = Stream.generate(() -> r.nextInt(maxElement)).limit(size).toArray(Integer[]::new);
//the element that should be found
Integer shouldBeFound = integers[r.nextInt(size - 1)];
LinearSearch search = new LinearSearch();
int atIndex = search.find(integers, shouldBeFound);
System.out.println(String.format("Should be found: %d. Found %d at index %d. An array length %d"
, shouldBeFound, integers[atIndex], atIndex, size));
}
}

View File

@ -0,0 +1,80 @@
package search;
import java.util.Scanner;
/**
* Program to perform Saddleback Search
* Given a sorted 2D array(elements are sorted across every row and column, assuming ascending order)
* of size n*m we can search a given element in O(n+m)
* <p>
* we start from bottom left corner
* if the current element is greater than the given element then we move up
* else we move right
* Sample Input:
* 5 5 ->Dimensions
* -10 -5 -3 4 9
* -6 -2 0 5 10
* -4 -1 1 6 12
* 2 3 7 8 13
* 100 120 130 140 150
* 140 ->element to be searched
* output: 4 3 // first value is row, second one is column
*
* @author Nishita Aggarwal
*/
public class SaddlebackSearch {
/**
* This method performs Saddleback Search
*
* @param arr The **Sorted** array in which we will search the element.
* @param row the current row.
* @param col the current column.
* @param key the element that we want to search for.
* @return The index(row and column) of the element if found.
* Else returns -1 -1.
*/
private static int[] find(int arr[][], int row, int col, int key) {
//array to store the answer row and column
int ans[] = {-1, -1};
if (row < 0 || col >= arr[row].length) {
return ans;
}
if (arr[row][col] == key) {
ans[0] = row;
ans[1] = col;
return ans;
}
//if the current element is greater than the given element then we move up
else if (arr[row][col] > key) {
return find(arr, row - 1, col, key);
}
//else we move right
return find(arr, row, col + 1, key);
}
/**
* Main method
*
* @param args Command line arguments
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
int arr[][];
int i, j, rows = sc.nextInt(), col = sc.nextInt();
arr = new int[rows][col];
for (i = 0; i < rows; i++) {
for (j = 0; j < col; j++) {
arr[i][j] = sc.nextInt();
}
}
int ele = sc.nextInt();
//we start from bottom left corner
int ans[] = find(arr, rows - 1, 0, ele);
System.out.println(ans[0] + " " + ans[1]);
sc.close();
}
}

View File

@ -0,0 +1,20 @@
package search;
/**
* The common interface of most searching algorithms
*
* @author Podshivalov Nikita (https://github.com/nikitap492)
*
**/
public interface SearchAlgorithm {
/**
*
* @param key is an element which should be found
* @param array is an array where the element should be found
* @param <T> Comparable type
* @return first found index of the element
*/
<T extends Comparable<T>> int find(T array[], T key);
}

View File

@ -0,0 +1,106 @@
package search;
import java.util.Arrays;
import java.util.Random;
import java.util.stream.Stream;
import static java.lang.String.format;
/**
*
*
*
* A ternary search algorithm is a technique in computer science for finding the minimum or maximum of a unimodal function
* The algorithm determines either that the minimum or maximum cannot be in the first third of the domain
* or that it cannot be in the last third of the domain, then repeats on the remaining third.
*
* Worst-case performance Θ(log3(N))
* Best-case performance O(1)
* Average performance Θ(log3(N))
* Worst-case space complexity O(1)
*
*
* @author Podshivalov Nikita (https://github.com/nikitap492)
*
* @see SearchAlgorithm
* @see IterativeBinarySearch
*
*/
public class TernarySearch implements SearchAlgorithm{
/**
* @param arr The **Sorted** array in which we will search the element.
* @param value The value that we want to search for.
* @return The index of the element if found.
* Else returns -1.
*/
@Override
public <T extends Comparable<T>> int find(T[] arr, T value){
return ternarySearch(arr, value, 0, arr.length - 1);
}
/**
* @param arr The **Sorted** array in which we will search the element.
* @param key The value that we want to search for.
* @param start The starting index from which we will start Searching.
* @param end The ending index till which we will Search.
* @return Returns the index of the Element if found.
* Else returns -1.
*/
private <T extends Comparable<T>> int ternarySearch(T[] arr, T key, int start, int end) {
if (start > end){
return -1;
}
/* First boundary: add 1/3 of length to start */
int mid1 = start + (end - start) / 3;
/* Second boundary: add 2/3 of length to start */
int mid2 = start + 2 * (end - start) / 3;
if (key.compareTo(arr[mid1]) == 0) {
return mid1;
}
else if (key.compareTo(arr[mid2]) == 0) {
return mid2;
}
/* Search the first (1/3) rd part of the array.*/
else if (key.compareTo(arr[mid1]) < 0) {
return ternarySearch(arr, key, start, --mid1);
}
/* Search 3rd (1/3)rd part of the array */
else if (key.compareTo(arr[mid2]) > 0) {
return ternarySearch(arr, key, ++mid2, end);
}
/* Search middle (1/3)rd part of the array */
else {
return ternarySearch(arr, key, mid1, mid2);
}
}
public static void main(String[] args) {
//just generate data
Random r = new Random();
int size = 100;
int maxElement = 100000;
Integer[] integers = Stream.generate(() -> r.nextInt(maxElement)).limit(size).sorted().toArray(Integer[]::new);
//the element that should be found
Integer shouldBeFound = integers[r.nextInt(size - 1)];
TernarySearch search = new TernarySearch();
int atIndex = search.find(integers, shouldBeFound);
System.out.println(format("Should be found: %d. Found %d at index %d. An array length %d"
, shouldBeFound, integers[atIndex], atIndex, size));
int toCheck = Arrays.binarySearch(integers, shouldBeFound);
System.out.println(format("Found by system method at an index: %d. Is equal: %b", toCheck, toCheck == atIndex));
}
}

View File

@ -1,62 +0,0 @@
// Java program for implementation of Comb Sort
class CombSort
{
// To find gap between elements
static int getNextGap(int gap)
{
// Shrink gap by Shrink factor
gap = (gap*10)/13;
gap = (gap < 1) ? 1: gap;
}
// Function to sort arr[] using Comb Sort
static void sort(int arr[])
{
int n = arr.length;
// initialize gap
int gap = n;
// 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 = getNextGap(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<n-gap; i++)
{
if (arr[i] > arr[i+gap])
{
// Swap arr[i] and arr[i+gap]
int temp = arr[i];
arr[i] = arr[i+gap];
arr[i+gap] = temp;
// Set swapped
swapped = true;
}
}
}
}
// Driver method
public static void main(String args[])
{
CombSort ob = new CombSort();
int arr[] = {8, 4, 1, 56, 3, -44, 23, -6, 28, 0};
ob.sort(arr);
System.out.println("sorted array");
for (int i=0; i<arr.length; ++i) {
System.out.print(arr[i] + " ");
}
}
}

View File

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

View File

@ -11,8 +11,18 @@ import java.util.List;
**/
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()])));