From ca8acc9fbe5be862c139304729fcfcaf844fbd8d Mon Sep 17 00:00:00 2001 From: Arica Chakraborty Date: Mon, 8 Oct 2018 12:12:46 +0530 Subject: [PATCH 1/2] Added counting sort java implementation --- counting_sort/Java/CountingSort.java | 43 ++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 counting_sort/Java/CountingSort.java diff --git a/counting_sort/Java/CountingSort.java b/counting_sort/Java/CountingSort.java new file mode 100644 index 00000000..ed231544 --- /dev/null +++ b/counting_sort/Java/CountingSort.java @@ -0,0 +1,43 @@ +/*Counting Sort algorithm- In Counting sort, the frequencies of distinct elements of the array +to be sorted is counted and stored in an auxiliary array, by mapping its value as an index of +the auxiliary array. +Time Complexity- The below algorithm takes time O(n+m) +where n= number of elements in the array to be sorted, and +m= size of the auxilliary array + +This is a linear time algorithm and can be used when a small nember of elements needs to be sorted. +*/ +public class CountingSort { + public static void main(String[] args) { + int[] array = {5,4,3,2,1}; + //find the maximum element from the array + int max = array[0]; + for (int i = 1; i < array.length;i++){ + if(array[i]>max){ + max= array[i]; + } + } + //declare an auxillary array + int[] auxArray= new int[max+1]; + for(int i=0;i0){ + sortedAux[j]=i; + j++; + temp--; + } + } + //printing the sorted array + for(int i=0;i Date: Mon, 8 Oct 2018 12:49:38 +0530 Subject: [PATCH 2/2] Added counting sort java implementation --- counting_sort/Java/CountingSort.java | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/counting_sort/Java/CountingSort.java b/counting_sort/Java/CountingSort.java index ed231544..8e134b37 100644 --- a/counting_sort/Java/CountingSort.java +++ b/counting_sort/Java/CountingSort.java @@ -1,5 +1,5 @@ /*Counting Sort algorithm- In Counting sort, the frequencies of distinct elements of the array -to be sorted is counted and stored in an auxiliary array, by mapping its value as an index of +to be sorted is counted and stored in an auxiliary array, by mapping its value as an index of the auxiliary array. Time Complexity- The below algorithm takes time O(n+m) where n= number of elements in the array to be sorted, and @@ -8,8 +8,7 @@ This is a linear time algorithm and can be used when a small nember of elements needs to be sorted. */ public class CountingSort { - public static void main(String[] args) { - int[] array = {5,4,3,2,1}; + static int[] countingSort(int[] array){ //find the maximum element from the array int max = array[0]; for (int i = 1; i < array.length;i++){ @@ -34,6 +33,11 @@ public static void main(String[] args) { temp--; } } + return sortedAux; + } + public static void main(String[] args) { + int[] array = {5,2,9,5,2,3,5}; + int[] sortedAux= countingSort(array); //printing the sorted array for(int i=0;i