diff --git a/Sorts/BinaryTreeSort.java b/Sorts/BinaryTreeSort.java deleted file mode 100644 index e6a80f62..00000000 --- a/Sorts/BinaryTreeSort.java +++ /dev/null @@ -1,80 +0,0 @@ -import java.util.Arrays; -public class TreeSort { - - public Node root; - - public TreeSort(Object x) { - root = new Node(x); - }//end TreeSort constructor - - public Node insert(Node node, Integer x) { - if (node == null) { - return node = new Node(x); - }//end if - if (x < (Integer) node.anElement) { - node.less = insert(node.less, x); - } //end if - else { - node.greater = insert(node.greater, x); - }//end else - return node; - }//end insert - - - public Node decimalInsert(Node node, Double x) { - if (node == null) { - return node = new Node(x); - }//end if - if (x < (Double) node.anElement) { - node.less = decimalInsert(node.less, x); - } //end if - else { - node.greater = decimalInsert(node.greater, x); - }//end else - return node; - }//end insert - - - public void treeSort(Node node) { - if (node != null) { - treeSort(node.less); - System.out.print(((Object) node.anElement) + ", "); - treeSort(node.greater); - }//end if - }//end TreeSort class - - - -public static void main(String args[]) { - int[] intArray = {12, 40, 9, 3, 19, 74, 7, 31, 23, 54, 26, 81, 12 }; - TreeSort ts = new TreeSort(new Integer(intArray[0])); - for (int i = 1; i < intArray.length; i++) { //sorts every index of the list one at a time - ts.insert(ts.root, new Integer(intArray[i])); //builds on the tree from a root node - }//end for - System.out.print("Integer Array Sorted in Increasing Order: "); - ts.treeSort(ts.root); - System.out.println(); //To sort a test array of integers - - Double[] decimalArray = {8.2, 1.5, 3.14159265, 9.3, 5.1, 4.8, 2.6}; - TreeSort dts = new TreeSort(new Double(decimalArray[0]).doubleValue()); - for (int i = 1; i < decimalArray.length; i++) { //sorts every index of the list one at a time - dts.decimalInsert(dts.root, new Double(decimalArray[i]).doubleValue()); //builds on the tree from a root node - }//end for - System.out.print("Decimal Array, Sorted in Increasing Order: "); - dts.treeSort(dts.root); - System.out.println(); - - String[] stringArray = {"c", "a", "e", "b","d", "dd","da","zz", "AA", "aa","aB","Hb", "Z"}; - int last = stringArray.length; - Arrays.sort(stringArray); //Uses an imported arrays method to automatically alphabetize - System.out.print("String Array Sorted in Alphabetical Order: "); - ts.insert(ts.root, last); - for(int i=0; i void swap(T array[], int first, int second){ - T randomElement = array[first]; - array[first] = array[second]; - array[second] = randomElement; - } - - private static > boolean isSorted(T array[]){ - for(int i = 0; i 0) return false; - } - return true; - } - - // Randomly shuffles the array - private static void nextPermutation(T array[]){ - int length = array.length; - Random random = new Random(); - - for (int i = 0; i < array.length; i++) { - int randomIndex = i + random.nextInt(length - i); - swap(array, randomIndex, i); - } - } - - public static > void bogoSort(T array[]) { - while(!isSorted(array)){ - nextPermutation(array); - } - } - - // Driver Program - public static void main(String[] args) - { - // Integer Input - int[] arr1 = {4,23,6,78,1,54,231,9,12}; - int last = arr1.length; - Integer[] array = new Integer[last]; - for (int i=0;i 1 4 6 9 12 23 54 78 231 - for(int i=0; i a b c d e - for(int i=0; i> void BS(T array[], int last) { - //Sorting - boolean swap; - do - { - swap = false; - for (int count = 0; count < last-1; count++) - { - int comp = array[count].compareTo(array[count + 1]); - if (comp > 0) - { - T temp = array[count]; - array[count] = array[count + 1]; - array[count + 1] = temp; - swap = true; - } - } - last--; - } while (swap); - } - - // Driver Program - public static void main(String[] args) - { - // Integer Input - int[] arr1 = {4,23,6,78,1,54,231,9,12}; - int last = arr1.length; - Integer[] array = new Integer[last]; - for (int i=0;i 1 4 6 9 12 23 54 78 231 - for(int i=0; i a b c d e - for(int i=0; i> void CS(T array[], int last) { - - // Sorting - boolean swap; - do { - swap = false; - - //front - for (int count = 0; count <= last - 2; count++) { - int comp = array[count].compareTo(array[count + 1]); - if (comp > 0) { - T aux = array[count]; - array[count] = array[count + 1]; - array[count + 1] = aux; - swap = true; - } - } - //break if no swap occurred - if (!swap) { - break; - } - swap = false; - - //back - for (int count = last - 2; count >= 0; count--) { - int comp = array[count].compareTo(array[count + 1]); - if (comp > 0) { - T aux = array[count]; - array[count] = array[count + 1]; - array[count + 1] = aux; - swap = true; - } - } - last--; - //end - } while (swap); - } - - // Driver Program - public static void main(String[] args) { - // Integer Input - int[] arr1 = { 4, 23, 6, 78, 1, 54, 231, 9, 12 }; - int last = arr1.length; - Integer[] array = new Integer[last]; - for (int i = 0; i < last; i++) { - array[i] = arr1[i]; - } - - CS(array, last); - - // Output => 1 4 6 9 12 23 54 78 231 - for (int i = 0; i < last; i++) { - System.out.print(array[i] + "\t"); - } - System.out.println(); - - // String Input - String[] array1 = { "c", "a", "e", "b", "d" }; - last = array1.length; - - CS(array1, last); - - // Output => a b c d e - for (int i = 0; i < last; i++) { - System.out.print(array1[i] + "\t"); - } - } -} diff --git a/Sorts/HeapSort.java b/Sorts/HeapSort.java deleted file mode 100644 index 6b3a3fdc..00000000 --- a/Sorts/HeapSort.java +++ /dev/null @@ -1,174 +0,0 @@ -import java.util.Scanner; - -/** - * Heap Sort Algorithm - * Implements MinHeap - * - * @author Unknown - * - */ -public class HeapSort { - /** Array to store heap */ - private int[] heap; - /** The size of the heap */ - private int size; - - /** - * Constructor - * - * @param heap array of unordered integers - */ - public HeapSort(int[] heap) { - this.setHeap(heap); - this.setSize(heap.length); - } - - /** - * Setter for variable size - * - * @param length new size - */ - private void setSize(int length) { - this.size = length; - } - - /** - * Setter for variable heap - * - * @param heap array of unordered elements - */ - private void setHeap(int[] heap) { - this.heap = heap; - } - - /** - * Swaps index of first with second - * - * @param first First index to switch - * @param second Second index to switch - */ - private void swap(int first, int second) { - int temp = this.heap[first]; - this.heap[first] = this.heap[second]; - this.heap[second] = temp; - } - - /** - * Heapifies subtree from top as root to last as last child - * - * @param rootIndex index of root - * @param lastChild index of last child - */ - private void heapSubtree(int rootIndex, int lastChild) { - int leftIndex = rootIndex * 2 + 1; - int rightIndex = rootIndex * 2 + 2; - int root = this.heap[rootIndex]; - if (rightIndex <= lastChild) { // if has right and left children - int left = this.heap[leftIndex]; - int right = this.heap[rightIndex]; - if (left < right && left < root) { - this.swap(leftIndex, rootIndex); - this.heapSubtree(leftIndex, lastChild); - } else if (right < root) { - this.swap(rightIndex, rootIndex); - this.heapSubtree(rightIndex, lastChild); - } - } else if (leftIndex <= lastChild) { // if no right child, but has left child - int left = this.heap[leftIndex]; - if (left < root) { - this.swap(leftIndex, rootIndex); - this.heapSubtree(leftIndex, lastChild); - } - } - } - - /** - * Makes heap with root as root - * - * @param root index of root of heap - */ - private void makeMinHeap(int root) { - int leftIndex = root * 2 + 1; - int rightIndex = root * 2 + 2; - boolean hasLeftChild = leftIndex < this.heap.length; - boolean hasRightChild = rightIndex < this.heap.length; - if (hasRightChild) { //if has left and right - this.makeMinHeap(leftIndex); - this.makeMinHeap(rightIndex); - this.heapSubtree(root, this.heap.length - 1); - } else if (hasLeftChild) { - this.heapSubtree(root, this.heap.length - 1); - } - } - - /** - * Gets the root of heap - * - * @return root of heap - */ - private int getRoot() { - this.swap(0, this.size - 1); - this.size--; - this.heapSubtree(0, this.size - 1); - return this.heap[this.size]; // return old root - } - - /** - * Sorts heap with heap sort; displays ordered elements to console. - * - * @return sorted array of sorted elements - */ - public final int[] sort() { - this.makeMinHeap(0); // make min heap using index 0 as root. - int[] sorted = new int[this.size]; - int index = 0; - while (this.size > 0) { - int min = this.getRoot(); - sorted[index] = min; - index++; - } - return sorted; - } - - /** - * Gets input to sort - * - * @return unsorted array of integers to sort - */ - public static int[] getInput() { - final int numElements = 6; - int[] unsorted = new int[numElements]; - Scanner input = new Scanner(System.in); - System.out.println("Enter any 6 Numbers for Unsorted Array : "); - for (int i = 0; i < numElements; i++) { - unsorted[i] = input.nextInt(); - } - input.close(); - return unsorted; - } - - /** - * Prints elements in heap - * - * @param heap array representing heap - */ - public static void printData(int[] heap) { - System.out.println("Sorted Elements:"); - for (int i = 0; i < heap.length; i++) { - System.out.print(" " + heap[i] + " "); - } - } - - /** - * Main method - * - * @param args the command line arguments - */ - public static void main(String[] args) { - int[] heap = getInput(); - HeapSort data = new HeapSort(heap); - int[] sorted = data.sort(); - printData(sorted); - } - -} diff --git a/Sorts/InsertionSort.java b/Sorts/InsertionSort.java deleted file mode 100644 index c77b895f..00000000 --- a/Sorts/InsertionSort.java +++ /dev/null @@ -1,63 +0,0 @@ -/** - * - * @author Varun Upadhyay (https://github.com/varunu28) - * - */ - -class InsertionSort { - - /** - * This method implements the Generic Insertion Sort - * - * @param array The array to be sorted - * @param last The count of total number of elements in array - * Sorts the array in increasing order - **/ - - public static > void IS(T array[], int last) { - T key; - for (int j=1;j=0 && key.compareTo(array[i]) < 0) { - array[i+1] = array[i]; - i--; - } - // Placing the key (Card) at its correct position in the sorted subarray - array[i+1] = key; - } - } - - // Driver Program - public static void main(String[] args) { - // Integer Input - int[] arr1 = {4,23,6,78,1,54,231,9,12}; - int last = arr1.length; - Integer[] array = new Integer[arr1.length]; - for (int i=0;i 1 4 6 9 12 23 54 78 231 - for (int i=0;i a b c d e - for(int i=0; i> void QS(List list, int left, int right) { - if (left>=right) { return } - else - { - int pivot = partition(array, left,right); - QS(list, left, pivot- 1); - QS(list, pivot + 1, right); - } - } - - /** - * This method finds the partition index for an array - * - * @param array The array to be sorted - * @param start The first index of an array - * @param end The last index of an array - * Finds the partition index of an array - **/ - - public static > int partition(List list, int left, int right) { - int mid=(left+right)/2; - T pivot=list.get(mid); - swap(list,mid,right); - while(left=0) - { - ++left; - } - if(left=0) - { - --right; - } - if(left> void swap(List list, int initial, int fin) { - E temp= list.get(initial); - list.set(initial,list.get(fin)); - list.set(fin,temp); - } - - // Driver Program - public static void main(String[] args) { - - // For integer input - ArrayList array = new ArrayList(9); - array = {3,4,1,32,0,2,44,111,5}; - - QS(array, 0, array.size()-1); - - //Output => 0 1 2 3 4 5 32 44 111 - for (int i=0;i array1=new ArrayList(5); - array1 = {"c", "a", "e", "b","d"}; - - QS(array1, 0,array1.size()-1); - - //Output => a b c d e - for(int i=0; i> void SS(T[] arr, int n) { - - for (int i=0;i 1 4 6 9 12 23 54 78 231 - for(int i=0; i a b c d e - for(int i=0; i= 1) { - for (int i = h; i < N; i++) { - for (int j = i; j >= h && less(array[j], array[j-h]); j -= h) { - exch(array, j, j - h); - } - } - - h /= 3; - } - } - - /** - * Helper method for exchanging places in array - * @param array The array which elements we want to swap - * @param i index of the first element - * @param j index of the second element - */ - private static void exch(Comparable[] array, int i, int j) { - Comparable swap = array[i]; - array[i] = array[j]; - array[j] = swap; - } - - /** - * This method checks if first element is less then the other element - * @param v first element - * @param w second element - * @return true if the first element is less then the second element - */ - private static boolean less(Comparable v, Comparable w) { - return v.compareTo(w) < 0; - } - - public static void main(String[] args) { - // Integer Input - int[] arr1 = {4,23,6,78,1,54,231,9,12}; - Integer[] array = new Integer[arr1.length]; - - for (int i=0;i> { + void visit(Node node); + } + + private static class SortVisitor> implements TreeVisitor { + + private final T[] array; + private int counter; + + SortVisitor(T[] array) { + this.array = array; + } + + @Override + public void visit(Node node) { + array[counter++] = node.value; + } + } + + private static class Node>{ + private T value; + private Node left; + private Node right; + + Node(T value) { + this.value = value; + } + + void insert(Node node) { + if (less(node.value, value)){ + if (left != null) left.insert(node); + else left = node; + } + else { + if (right != null) right.insert(node); + else right = node; + } + } + + void traverse(TreeVisitor visitor) { + if ( left != null) + left.traverse(visitor); + + visitor.visit(this); + + if ( right != null ) + right.traverse(visitor ); + } + + } + + + @Override + public > T[] sort(T[] array) { + + Node root = new Node<>(array[0]); + for (int i = 1; i < array.length; i++) { + root.insert(new Node<>(array[i])); + } + + root.traverse(new SortVisitor<>(array)); + + return array; + } + + + public static void main(String args[]) { + + Integer[] intArray = {12, 40, 9, 3, 19, 74, 7, 31, 23, 54, 26, 81, 12}; + BinaryTreeSort treeSort = new BinaryTreeSort(); + Integer[] sorted = treeSort.sort(intArray); + print(sorted); + + Double[] decimalArray = {8.2, 1.5, 3.14159265, 9.3, 5.1, 4.8, 2.6}; + print(treeSort.sort(decimalArray)); + + String[] stringArray = {"c", "a", "e", "b","d", "dd","da","zz", "AA", "aa","aB","Hb", "Z"}; + print(treeSort.sort(stringArray)); + } + +} + diff --git a/Sorts/src/sort/BogoSort.java b/Sorts/src/sort/BogoSort.java new file mode 100644 index 00000000..1079ca21 --- /dev/null +++ b/Sorts/src/sort/BogoSort.java @@ -0,0 +1,59 @@ +package sort; + +import java.util.Random; + +import static sort.SortUtils.*; + + +/** + * + * @author Podshivalov Nikita (https://github.com/nikitap492) + * + * @see SortAlgorithm + * + */ +public class BogoSort implements SortAlgorithm { + + private static final Random random = new Random(); + + + private static > boolean isSorted(T array[]){ + for(int i = 0; i void nextPermutation(T array[]){ + int length = array.length; + + for (int i = 0; i < array.length; i++) { + int randomIndex = i + random.nextInt(length - i); + swap(array, randomIndex, i); + } + } + + public > T[] sort(T array[]) { + while(!isSorted(array)){ + nextPermutation(array); + } + return array; + } + + // Driver Program + public static void main(String[] args) { + // Integer Input + Integer[] integers = {4, 23, 6, 78, 1, 54, 231, 9, 12}; + + BogoSort bogoSort = new BogoSort(); + + // print a sorted array + print(bogoSort.sort(integers)); + + // String Input + String[] strings = {"c", "a", "e", "b","d"}; + + print(bogoSort.sort(strings)); + } +} diff --git a/Sorts/src/sort/BubbleSort.java b/Sorts/src/sort/BubbleSort.java new file mode 100644 index 00000000..99f63907 --- /dev/null +++ b/Sorts/src/sort/BubbleSort.java @@ -0,0 +1,55 @@ +package sort; + +import static sort.SortUtils.*; + +/** + * + * @author Varun Upadhyay (https://github.com/varunu28) + * @author Podshivalov Nikita (https://github.com/nikitap492) + * + * @see SortAlgorithm + */ + +class BubbleSort implements SortAlgorithm { + /** + * This method implements the Generic Bubble Sort + * + * @param array The array to be sorted + * Sorts the array in increasing order + **/ + + @Override + public > T[] sort(T array[]) { + int last = array.length; + //Sorting + boolean swap; + do { + swap = false; + for (int count = 0; count < last-1; count++) { + if (less(array[count], array[count + 1])) { + swap = swap(array, count, count + 1); + } + } + last--; + } while (swap); + return array; + } + + // Driver Program + public static void main(String[] args) { + + // Integer Input + Integer[] integers = {4, 23, 6, 78, 1, 54, 231, 9, 12}; + BubbleSort bubbleSort = new BubbleSort(); + bubbleSort.sort(integers); + + // Output => 1 4 6 9 12 23 54 78 231 + print(integers); + + // String Input + String[] strings = {"c", "a", "e", "b","d"}; + //Output => a b c d e + print(bubbleSort.sort(strings)); + + } +} diff --git a/Sorts/src/sort/CocktailShakerSort.java b/Sorts/src/sort/CocktailShakerSort.java new file mode 100644 index 00000000..b5da0df5 --- /dev/null +++ b/Sorts/src/sort/CocktailShakerSort.java @@ -0,0 +1,70 @@ +package sort; + +import static sort.SortUtils.*; + +/** + * + * @author Mateus Bizzo (https://github.com/MattBizzo) + * @author Podshivalov Nikita (https://github.com/nikitap492) + * + */ + +class CocktailShakerSort implements SortAlgorithm { + + /** + * This method implements the Generic Cocktail Shaker Sort + * + * @param array The array to be sorted + * Sorts the array in increasing order + **/ + + @Override + public > T[] sort(T[] array){ + + int last = array.length; + + // Sorting + boolean swap; + do { + swap = false; + + //front + for (int count = 0; count <= last - 2; count++) { + if (less(array[count + 1], array[count])) { + swap = swap(array, count, count + 1); + } + } + //break if no swap occurred + if (!swap) { + break; + } + swap = false; + + //back + for (int count = last - 2; count >= 0; count--) { + if (less(array[count + 1], array[count])) { + swap = swap(array, count, count + 1); + } + } + last--; + //end + } while (swap); + return array; + } + + // Driver Program + public static void main(String[] args) { + // Integer Input + Integer[] integers = { 4, 23, 6, 78, 1, 54, 231, 9, 12 }; + CocktailShakerSort shakerSort = new CocktailShakerSort(); + + // Output => 1 4 6 9 12 23 54 78 231 + print(shakerSort.sort(integers)); + + // String Input + String[] strings = { "c", "a", "e", "b", "d" }; + print(shakerSort.sort(strings)); + } + + +} diff --git a/Sorts/CountingSort.java b/Sorts/src/sort/CountingSort.java similarity index 70% rename from Sorts/CountingSort.java rename to Sorts/src/sort/CountingSort.java index e93afb0c..39442a00 100644 --- a/Sorts/CountingSort.java +++ b/Sorts/src/sort/CountingSort.java @@ -1,12 +1,12 @@ -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.TreeMap; +package sort; + +import java.util.*; import java.util.stream.IntStream; import java.util.stream.Stream; import static java.util.stream.Collectors.toList; import static java.util.stream.Collectors.toMap; +import static sort.SortUtils.print; /** * @@ -14,7 +14,14 @@ import static java.util.stream.Collectors.toMap; * @author Podshivalov Nikita (https://github.com/nikitap492) * */ -class CountingSort { +class CountingSort implements SortAlgorithm { + + + + @Override + public > T[] sort(T[] unsorted) { + return sort(Arrays.asList(unsorted)).toArray(unsorted); + } /** * This method implements the Generic Counting Sort @@ -24,7 +31,8 @@ class CountingSort { * Sorts the list in increasing order * The method uses list elements as keys in the frequency map **/ - public static > List countingSort(List list) { + @Override + public > List sort(List list) { Map frequency = new TreeMap<>(); // The final output array @@ -46,12 +54,12 @@ class CountingSort { /** * Stream Counting Sort - * The same as method {@link CountingSort#countingSort(List)} but this method uses stream API + * The same as method {@link CountingSort#sort(List)} } but this method uses stream API * * @param list The list to be sorted * **/ - public static > List streamCountingSort(List list) { + private static > List streamSort(List list) { return list.stream() .collect(toMap(k -> k, v -> 1, (v1, v2) -> v1 + v2, TreeMap::new)) .entrySet() @@ -64,15 +72,16 @@ class CountingSort { public static void main(String[] args) { // Integer Input List unsortedInts = Stream.of(4, 23, 6, 78, 1, 54, 23, 1, 9, 231, 9, 12).collect(toList()); + CountingSort countingSort = new CountingSort(); System.out.println("Before Sorting:"); - printList(unsortedInts); + print(unsortedInts); // Output => 1 1 4 6 9 9 12 23 23 54 78 231 System.out.println("After Sorting:"); - printList(countingSort(unsortedInts)); + print(countingSort.sort(unsortedInts)); System.out.println("After Sorting By Streams:"); - printList(streamCountingSort(unsortedInts)); + print(streamSort(unsortedInts)); System.out.println("\n------------------------------\n"); @@ -80,27 +89,14 @@ class CountingSort { List unsortedStrings = Stream.of("c", "a", "e", "b","d", "a", "f", "g", "c").collect(toList()); System.out.println("Before Sorting:"); - printList(unsortedStrings); + print(unsortedStrings); //Output => a a b c c d e f g System.out.println("After Sorting:"); - printList(countingSort(unsortedStrings)); + print(countingSort.sort(unsortedStrings)); System.out.println("After Sorting By Streams:"); - printList(streamCountingSort(unsortedStrings)); + print(streamSort(unsortedStrings)); } - - /** - * Just print list - * @param toPrint - a list which should be printed - */ - private static void printList(List toPrint){ - toPrint.stream() - .map(Object::toString) - .map(str -> str + " ") - .forEach(System.out::print); - - System.out.println(); - } } diff --git a/Sorts/src/sort/CycleSort.java b/Sorts/src/sort/CycleSort.java new file mode 100644 index 00000000..ea4f0553 --- /dev/null +++ b/Sorts/src/sort/CycleSort.java @@ -0,0 +1,81 @@ +package sort; + +import static sort.SortUtils.less; +import static sort.SortUtils.print; + +/** + * @author Podshivalov Nikita (https://github.com/nikitap492) + */ +class CycleSort implements SortAlgorithm { + + + @Override + public > T[] sort(T[] arr) { + int n = arr.length; + + // traverse array elements + for (int j = 0; j <= n - 2; j++) { + // initialize item as starting point + T item = arr[j]; + + // Find position where we put the item. + int pos = j; + for (int i = j + 1; i < n; i++) + if (less(arr[i], item)) pos++; + + // If item is already in correct position + if (pos == j) continue; + + // ignore all duplicate elements + while (item.compareTo(arr[pos]) == 0) + pos += 1; + + // put the item to it's right position + if (pos != j) { + item = replace(arr, pos, item); + } + + // Rotate rest of the cycle + while (pos != j) { + pos = j; + + // Find position where we put the element + for (int i = j + 1; i < n; i++) + if (less(arr[i], item)){ + pos += 1; + } + + + // ignore all duplicate elements + while (item.compareTo(arr[pos]) == 0) + pos += 1; + + // put the item to it's right position + if (item != arr[pos]) { + item = replace(arr, pos, item); + } + } + } + + return arr; + } + + private > T replace(T[] arr, int pos, T item){ + T temp = item; + item = arr[pos]; + arr[pos] = temp; + return item; + } + + + + public static void main(String[] args) { + Integer arr[] = { 4, 23, 6, 78, 1, 26, 11, 23 , 0, -6, 3, 54, 231, 9, 12 }; + CycleSort cycleSort = new CycleSort(); + cycleSort.sort(arr); + + System.out.println("After sort : "); + print(arr); + } + +} diff --git a/Sorts/src/sort/GnomeSort.java b/Sorts/src/sort/GnomeSort.java new file mode 100644 index 00000000..14af67c6 --- /dev/null +++ b/Sorts/src/sort/GnomeSort.java @@ -0,0 +1,44 @@ +package sort; + +import static sort.SortUtils.*; + +/** + * Implementation of gnome sort + * + * @author Podshivalov Nikita (https://github.com/nikitap492) + * @since 2018-04-10 + * + **/ +public class GnomeSort implements SortAlgorithm{ + + @Override + public > T[] sort(T[] arr) { + int i = 1; + int j = 2; + while (i < arr.length){ + if ( less(arr[i - 1], arr[i]) ) i = j++; + else { + swap(arr, i - 1, i); + if (--i == 0){ i = j++; } + } + } + + return null; + } + + public static void main(String[] args) { + Integer[] integers = { 4, 23, 6, 78, 1, 26, 11, 23 , 0, -6, 3, 54, 231, 9, 12 }; + String[] strings = {"c", "a", "e", "b","d", "dd","da","zz", "AA", "aa","aB","Hb", "Z"}; + GnomeSort gnomeSort = new GnomeSort(); + + gnomeSort.sort(integers); + gnomeSort.sort(strings); + + System.out.println("After sort : "); + print(integers); + print(strings); + + + } + +} diff --git a/Sorts/src/sort/HeapSort.java b/Sorts/src/sort/HeapSort.java new file mode 100644 index 00000000..6fab3747 --- /dev/null +++ b/Sorts/src/sort/HeapSort.java @@ -0,0 +1,131 @@ +package sort; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import static sort.SortUtils.*; + +/** + * Heap Sort Algorithm + * Implements MinHeap + * + * @author Podshivalov Nikita (https://github.com/nikitap492) + * + */ +public class HeapSort implements SortAlgorithm { + + + private static class Heap> { + /** Array to store heap */ + private T[] heap; + + /** + * Constructor + * + * @param heap array of unordered integers + */ + public Heap(T[] heap) { + this.heap = heap; + } + + /** + * Heapifies subtree from top as root to last as last child + * + * @param rootIndex index of root + * @param lastChild index of last child + */ + private void heapSubtree(int rootIndex, int lastChild) { + int leftIndex = rootIndex * 2 + 1; + int rightIndex = rootIndex * 2 + 2; + T root = heap[rootIndex]; + if (rightIndex <= lastChild) { // if has right and left children + T left = heap[leftIndex]; + T right = heap[rightIndex]; + if (less(left, right) && less(left, root)) { + swap(heap, leftIndex, rootIndex); + heapSubtree(leftIndex, lastChild); + } else if (less(right, root)) { + swap(heap, rightIndex, rootIndex); + heapSubtree(rightIndex, lastChild); + } + } else if (leftIndex <= lastChild) { // if no right child, but has left child + T left = heap[leftIndex]; + if (less(left, root)) { + swap(heap, leftIndex, rootIndex); + heapSubtree(leftIndex, lastChild); + } + } + } + + + /** + * Makes heap with root as root + * + * @param root index of root of heap + */ + private void makeMinHeap(int root) { + int leftIndex = root * 2 + 1; + int rightIndex = root * 2 + 2; + boolean hasLeftChild = leftIndex < heap.length; + boolean hasRightChild = rightIndex < heap.length; + if (hasRightChild) { //if has left and right + makeMinHeap(leftIndex); + makeMinHeap(rightIndex); + heapSubtree(root, heap.length - 1); + } else if (hasLeftChild) { + heapSubtree(root, heap.length - 1); + } + } + + /** + * Gets the root of heap + * + * @return root of heap + */ + private T getRoot(int size) { + swap(heap, 0, size); + heapSubtree(0, size - 1); + return heap[size]; // return old root + } + + + + + + } + + @Override + public > T[] sort(T[] unsorted) { + return sort(Arrays.asList(unsorted)).toArray(unsorted); + } + + @Override + public > List sort(List unsorted) { + int size = unsorted.size(); + + @SuppressWarnings("unchecked") + Heap heap = new Heap<>(unsorted.toArray((T[]) new Comparable[unsorted.size()])); + + heap.makeMinHeap(0); // make min heap using index 0 as root. + List sorted = new ArrayList<>(size); + while (size > 0) { + T min = heap.getRoot(--size); + sorted.add(min); + } + + return sorted; + } + + /** + * Main method + * + * @param args the command line arguments + */ + public static void main(String[] args) { + Integer[] heap = {4, 23, 6, 78, 1, 54, 231, 9, 12}; + HeapSort heapSort = new HeapSort(); + print(heapSort.sort(heap)); + } + +} diff --git a/Sorts/src/sort/InsertionSort.java b/Sorts/src/sort/InsertionSort.java new file mode 100644 index 00000000..59361430 --- /dev/null +++ b/Sorts/src/sort/InsertionSort.java @@ -0,0 +1,61 @@ +package sort; + +import static sort.SortUtils.less; +import static sort.SortUtils.print; + +/** + * + * @author Varun Upadhyay (https://github.com/varunu28) + * @author Podshivalov Nikita (https://github.com/nikitap492) + * + */ + +class InsertionSort implements SortAlgorithm { + + /** + * This method implements the Generic Insertion Sort + * Sorts the array in increasing order + * + * @param array The array to be sorted + * + **/ + + @Override + public > T[] sort(T[] array) { + for (int j = 1; j < array.length; j++) { + + // Picking up the key(Card) + T key = array[j]; + int i = j - 1; + + while (i >= 0 && less(key, array[i])) { + array[i + 1] = array[i]; + i--; + } + // Placing the key (Card) at its correct position in the sorted subarray + array[i + 1] = key; + } + return array; + } + + // Driver Program + public static void main(String[] args) { + // Integer Input + Integer[] integers = {4, 23, 6, 78, 1, 54, 231, 9, 12}; + + InsertionSort sort = new InsertionSort(); + + sort.sort(integers); + + // Output => 1 4 6 9 12 23 54 78 231 + print(integers); + + // String Input + String[] strings = {"c", "a", "e", "b","d"}; + + sort.sort(strings); + + //Output => a b c d e + print(strings); + } +} diff --git a/Sorts/MergeSort.java b/Sorts/src/sort/MergeSort.java similarity index 53% rename from Sorts/MergeSort.java rename to Sorts/src/sort/MergeSort.java index b53451af..4f294dc7 100644 --- a/Sorts/MergeSort.java +++ b/Sorts/src/sort/MergeSort.java @@ -1,13 +1,37 @@ +package sort; + +import static sort.SortUtils.print; + /** + * This method implements the Generic Merge Sort + * * * @author Varun Upadhyay (https://github.com/varunu28) + * @author Podshivalov Nikita (https://github.com/nikitap492) + * + * + * @see SortAlgorithm * */ -class MergeSort { +class MergeSort implements SortAlgorithm { + /** * This method implements the Generic Merge Sort + * @param unsorted the array which should be sorted + * @param Comparable class + * @return sorted array + */ + @Override + @SuppressWarnings("unchecked") + public > T[] sort(T[] unsorted) { + T[] tmp = (T[]) new Comparable[unsorted.length]; + doSort(unsorted, tmp, 0, unsorted.length - 1); + return unsorted; + } + + /** * * @param arr The array to be sorted * @param temp The copy of the actual array @@ -15,12 +39,11 @@ class MergeSort { * @param right The last index of the array * Recursively sorts the array in increasing order **/ - - public static > void MS(T[] arr, T[] temp, int left, int right) { + private static > void doSort(T[] arr, T[] temp, int left, int right) { if (left < right) { int mid = left + (right - left) / 2; - MS(arr, temp, left, mid); - MS(arr, temp,mid + 1, right); + doSort(arr, temp, left, mid); + doSort(arr, temp,mid + 1, right); merge(arr, temp, left, mid, right); } @@ -37,16 +60,15 @@ class MergeSort { * merges two parts of an array in increasing order **/ - public static > void merge(T[] arr, T[] temp, int left, int mid, int right) { - for (int i=left;i<=right;i++) { - temp[i] = arr[i]; - } + private static > void merge(T[] arr, T[] temp, int left, int mid, int right) { + System.arraycopy(arr, left, temp, left, right - left + 1); + int i= left; int j = mid + 1; int k = left; - while (i<=mid && j<=right) { + while (i <= mid && j <= right) { if (temp[i].compareTo(temp[j]) <= 0) { arr[k] = temp[i]; i++; @@ -69,32 +91,17 @@ class MergeSort { public static void main(String[] args) { // Integer Input - int[] arr = {4,23,6,78,1,54,231,9,12}; - Integer[] array = new Integer[arr.length]; - for (int i=0;i 1 4 6 9 12 23 54 78 231 - for (int i=0;i a b c d e - for(int i=0; i> 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); + } + + + + + +} diff --git a/Sorts/src/sort/QuickSort.java b/Sorts/src/sort/QuickSort.java new file mode 100644 index 00000000..4159fc82 --- /dev/null +++ b/Sorts/src/sort/QuickSort.java @@ -0,0 +1,97 @@ +package sort; + +import static sort.SortUtils.*; + +/** + * + * @author Varun Upadhyay (https://github.com/varunu28) + * @author Podshivalov Nikita (https://github.com/nikitap492) + * + * + * @see SortAlgorithm + * + */ +class QuickSort implements SortAlgorithm { + + + + /** + * This method implements the Generic Quick Sort + * + * @param array The array to be sorted + * Sorts the array in increasing order + **/ + + @Override + public > T[] sort(T[] array) { + doSort(array, 0, array.length - 1); + return array; + } + + + /** + * The sorting process + * + * @param left The first index of an array + * @param right The last index of an array + * @param array The array to be sorted + * + **/ + + private static > void doSort(T[] array, int left, int right) { + if (left < right) { + int pivot = partition(array, left, right); + doSort(array, left, pivot - 1); + doSort(array, pivot , right); + } + } + + /** + * This method finds the partition index for an array + * + * @param array The array to be sorted + * @param left The first index of an array + * @param right The last index of an array + * Finds the partition index of an array + **/ + + private static > int partition(T[] array, int left, int right) { + int mid = (left + right) / 2; + T pivot = array[mid]; + + while(left <= right) { + while(less(array[left], pivot)){ + ++left; + } + while(less(pivot, array[right])) { + --right; + } + if(left <= right) { + swap(array, left, right); + ++left; + --right; + } + } + return left; + } + + // Driver Program + public static void main(String[] args) { + + // For integer input + Integer[] array = {3, 4, 1, 32, 0, 1, 5, 12 ,2, 5 ,7 ,8 ,9, 2, 44, 111, 5}; + + QuickSort quickSort = new QuickSort(); + // quickSort.sort(array); + + //Output => 0 1 1 2 2 3 4 5 5 5 7 8 9 12 32 44 111 + print(array); + + String[] stringArray = {"c", "a", "e", "b", "d"}; + quickSort.sort(stringArray); + + //Output => a b c d e + print(stringArray); + } +} + diff --git a/Sorts/radixSort.java b/Sorts/src/sort/RadixSort.java similarity index 83% rename from Sorts/radixSort.java rename to Sorts/src/sort/RadixSort.java index 5afacad8..0d1e6966 100644 --- a/Sorts/radixSort.java +++ b/Sorts/src/sort/RadixSort.java @@ -1,18 +1,19 @@ -import java.util.*; +package sort; + +import java.util.Arrays; -class Radix { +class RadixSort { - static int getMax(int arr[], int n) - { + private static int getMax(int arr[], int n) { int mx = arr[0]; for (int i = 1; i < n; i++) if (arr[i] > mx) mx = arr[i]; return mx; } - - static void countSort(int arr[], int n, int exp) + + private static void countSort(int arr[], int n, int exp) { int output[] = new int[n]; int i; @@ -35,8 +36,7 @@ class Radix { arr[i] = output[i]; } - static void radixsort(int arr[], int n) - { + private static void radixsort(int arr[], int n) { int m = getMax(arr, n); diff --git a/Sorts/src/sort/SelectionSort.java b/Sorts/src/sort/SelectionSort.java new file mode 100644 index 00000000..960215a6 --- /dev/null +++ b/Sorts/src/sort/SelectionSort.java @@ -0,0 +1,63 @@ +package sort; + +import static sort.SortUtils.*; + +/** + * + * @author Varun Upadhyay (https://github.com/varunu28) + * @author Podshivalov Nikita (https://github.com/nikitap492) + * + * @see SortAlgorithm + * + */ + +public class SelectionSort implements SortAlgorithm { + + /** + * This method implements the Generic Selection Sort + * + * @param arr The array to be sorted + * Sorts the array in increasing order + **/ + @Override + public > T[] sort(T[] arr) { + int n = arr.length; + for (int i = 0; i < n - 1; i++) { + // Initial index of min + int min = i; + + for (int j = i +1 ; j < n; j++) { + if (less(arr[j], arr[min])) { + min = j; + } + } + + // Swapping if index of min is changed + if (min != i) { + swap(arr, i , min); + } + } + + return arr; + } + + // Driver Program + public static void main(String[] args) { + + Integer[] arr = {4, 23, 6, 78, 1, 54, 231, 9, 12}; + + SelectionSort selectionSort = new SelectionSort(); + + Integer[] sorted = selectionSort.sort(arr); + + // Output => 1 4 6 9 12 23 54 78 231 + print(sorted); + + // String Input + String[] strings = {"c", "a", "e", "b","d"}; + String[] sortedStrings = selectionSort.sort(strings); + + //Output => a b c d e + print(sortedStrings); + } +} diff --git a/Sorts/src/sort/ShellSort.java b/Sorts/src/sort/ShellSort.java new file mode 100644 index 00000000..bafd19b1 --- /dev/null +++ b/Sorts/src/sort/ShellSort.java @@ -0,0 +1,50 @@ +package sort; + +import static sort.SortUtils.*; + + +/** + * @author dpunosevac + * @author Podshivalov Nikita (https://github.com/nikitap492) + * + * @see SortAlgorithm + * + */ +public class ShellSort implements SortAlgorithm { + + /** + * This method implements Generic Shell Sort. + * @param array The array to be sorted + */ + @Override + public > T[] sort(T[] array) { + int N = array.length; + int h = 1; + + while (h < N/3) { + h = 3 * h + 1; + } + + while (h >= 1) { + for (int i = h; i < N; i++) { + for (int j = i; j >= h && less(array[j], array[j-h]); j -= h) { + swap(array, j, j - h); + } + } + + h /= 3; + } + + return array; + } + + public static void main(String[] args) { + Integer[] toSort = {4, 23, 6, 78, 1, 54, 231, 9, 12}; + + ShellSort sort = new ShellSort(); + Integer[] sorted = sort.sort(toSort); + + print(sorted); + + } +} diff --git a/Sorts/src/sort/SortAlgorithm.java b/Sorts/src/sort/SortAlgorithm.java new file mode 100644 index 00000000..6725d187 --- /dev/null +++ b/Sorts/src/sort/SortAlgorithm.java @@ -0,0 +1,21 @@ +package sort; + +import java.util.Arrays; +import java.util.List; + +/** + * The common interface of most algorithms + * + * @author Podshivalov Nikita (https://github.com/nikitap492) + * + **/ +public interface SortAlgorithm { + + > T[] sort(T[] unsorted); + + @SuppressWarnings("unchecked") + default > List sort(List unsorted){ + return Arrays.asList(sort(unsorted.toArray((T[]) new Comparable[unsorted.size()]))); + } + +} diff --git a/Sorts/src/sort/SortUtils.java b/Sorts/src/sort/SortUtils.java new file mode 100644 index 00000000..8766e9d0 --- /dev/null +++ b/Sorts/src/sort/SortUtils.java @@ -0,0 +1,75 @@ +package sort; + +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 + * @param array The array which elements we want to swap + * @param idx index of the first element + * @param idy index of the second element + */ + static boolean swap(T[] array, int idx, int idy){ + T swap = array[idx]; + array[idx] = array[idy]; + array[idy] = swap; + return true; + } + + + /** + * This method checks if first element is less then the other element + * @param v first element + * @param w second element + * @return true if the first element is less then the second element + */ + static > boolean less(T v, T w) { + return v.compareTo(w) < 0; + } + + + /** + * Just print list + * @param toPrint - a list which should be printed + */ + static void print(List toPrint){ + toPrint.stream() + .map(Object::toString) + .map(str -> str + " ") + .forEach(System.out::print); + + System.out.println(); + } + + + /** + * Prints an array + * @param toPrint - the array which should be printed + */ + static void print(Object[] 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 > void flip(T[] array, int left, int right) { + while (left <= right) { + swap(array, left++ , right--); + } + } +}