Add Counting Sort - java (#124)

* Add CountingSort.java

* File name and Readme sorting

* static main and print array
pull/125/head
Valerio Trinca 2021-03-30 14:17:14 +02:00 committed by GitHub
parent 3f1e345411
commit 32fa3fdc15
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 75 additions and 0 deletions

View File

@ -37,6 +37,7 @@
3. [Selection Sort](java/selection-sort.java) 3. [Selection Sort](java/selection-sort.java)
4. [Merge Sort](java/merge-sort.java) 4. [Merge Sort](java/merge-sort.java)
5. [Quick Sort](java/quick-sort.java) 5. [Quick Sort](java/quick-sort.java)
6. [Counting Sort](java/counting-sort.java)
### JavaScript ### JavaScript

View File

@ -0,0 +1,74 @@
public class CountingSort {
/**
* Public method to use the counting sort algortithm
* @param arr - the array in input
*/
public void sort(int[] arr){
int[] sortedArray = new int[arr.length + 1];
// Search max element
int max = arr[0];
for(int i = 0; i < arr.length; i++){
if(arr[i] > max){
max = arr[i];
}
}
// Create counting array
int[] countArray = new int[max + 1];
for(int i = 0; i < countArray.length; i++){
countArray[i] = 0;
}
// Count elements in array
for(int i = 0; i < arr.length; i++){
countArray[arr[i]]++;
}
for(int i = 1; i < countArray.length; i++){
countArray[i] += countArray[i - 1];
}
for (int i = arr.length - 1; i >= 0; i--) {
sortedArray[countArray[arr[i]] - 1] = arr[i];
countArray[arr[i]]--;
}
System.arraycopy(sortedArray, 0, arr, 0, arr.length);
}
/**
* Main method for testing
* @param args
*/
public static void main(String[] args) throws Exception {
CountingSort count = new CountingSort();
int[] test = {1,9,8,7,6,5,4,3,2,12,546,23,123,5768,689,45,6342,0,76,856,34,412,12,32,353,46,568,456,234,3456,467,345345,345,345,};
count.sort(test);
for(int i = 1; i < test.length; i++){
if(test[i] < test[i - 1]){
throw new Exception("[ERROR] Ops! Counting sort not work!");
}
}
printArray(test);
}
/**
* Print an array
* @param arr
*/
public static void printArray(int[] arr){
System.out.println("Sorted array: ");
for(int i = 0; i < arr.length; i++){
System.out.println(" " + i);
}
}
}