Counting sort ............123

code given on geeksforgeeks I don’t understand

int max = Arrays.stream(arr).max().getAsInt();
int min = Arrays.stream(arr).min().getAsInt();
whats this?

@Dhruv-Goyal-449223618988467
int max = Arrays.stream(arr).max().getAsInt();
int min = Arrays.stream(arr).min().getAsInt();
Arrays.stream(arr) is inbuilt function to get max and min without writing the iterative for loop to get max and min.

ya clear till 2nd point, difficulty in 3rd point, pls used to send chatting link on emails.

let array is 1,4,1,5,1,5
then what this int min = Arrays.stream(arr).min().getAsInt(); gives in ans
is it 1 or 0
and if consider neg integers what this gives,neg of taken array

@Dhruv-Goyal-449223618988467
Arrays.stream(arr).min().getAsInt() will give 1 as an answer,as it is just shortcut to find minimum element in the Array.
Array: 1,4,1,5,1,5 is having 1 as its minimum.
Now for the negative part:
Consider an array of -1,0,-3,-2,10.
The Array is having -3 as minimum,hence Arrays.stream(arr).min().getAsInt() will give -3 as an answer in this array.

As i saw algo on geeksforgeeks
Suppose array is 1,3,1,5,1,5
for(i=0,i<arr.len,i++)
Count[arr[i]-min]++.
Let i=5 ,arr[i]=5
But arr[i]-min=5-1=4 (bcoz min =1)
Count[4] get incremented to 1 from 0
But i want to increment arr[5] bcoz 5 occurs multiple times and 4 not occur a single time

@Dhruv-Goyal-449223618988467
There are 4 major steps in this code:

int max = Arrays.stream(arr).max().getAsInt();
int min = Arrays.stream(arr).min().getAsInt();
int range = max - min + 1;
int count[] = new int[range];
int output[] = new int[arr.length];
for (int i = 0; i < arr.length; i++)
{
count[arr[i] - min]++;
}

    for (int i = 1; i < count.length; i++)  
    { 
        count[i] += count[i - 1]; 
    } 

    for (int i = arr.length - 1; i >= 0; i--)  
    { 
        output[count[arr[i] - min] - 1] = arr[i]; 
        count[arr[i] - min]--; 
    } 

    for (int i = 0; i < arr.length; i++) 
    { 
        arr[i] = output[i]; 
    } 

This code is doing one extra work that it is also handling non-positive numbers.

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.