Counting sort iterating from start - algorithm

I have seen other questions on SO asking why the last iteration in counting sort, where we place elements on the sorted array cannot start from the start. The reason is that that way the sort algorithm loses its stability.
But what if we reversed the count also? Instead of counting the no of elements present before a specific element, what if we count the no of elements present after that specific element? I have implemented it like the following.
public class TestCountSort {
public static void main(String[] args) {
Element[] arr=new Element[]{new Element("One",1),new Element("Three",2),new Element("Two",1)};
System.out.println("Array before - "+Arrays.toString(arr));
countSort(arr);
System.out.println("Array after - "+Arrays.toString(arr));
}
public static void countSort(Element[] arr){
int n=arr.length;
int max=arr[0].key;
int min=arr[0].key;
for(Element i:arr){
if(i.key>max){
max=i.key;
}
if(i.key<min){
min=i.key;
}
}
int range=max-min+1;
int[] count=new int[range];
Element[] sortedArray=new Element[n];
for(Element i:arr){
count[i.key-min]++;
}
for(int i=range-2;i>=0;i--){
count[i]=count[i]+count[i+1];
}
for(int i=0;i<n;i++){
sortedArray[n-count[arr[i].key-min]]=arr[i];
count[arr[i].key-min]--;
}
for(int i=0;i<n;i++){
arr[i]=sortedArray[i];
}
}
}
class Element{
private String name;
public int key;
public Element(String name, int key){
this.name=name;
this.key=key;
}
public String toString(){
return "{"+name+":"+key+"}";
}
}
Will this preserve the stability and provide sorting? Or is there something I am missing?

Related

how to make a loop of the amount of space in a train

I want to make a train and at every stop is says how many people are coming in and going out, and if the maximum is reached, then it declines the rest. I also have seated spots and standing spots and if there are any seated spots left, the standing people go sit instead of stand.
so here is what I have
public class Train {
private int declinedPassengers; // instance variables
private int passengerInTrain;
private int numberOfSeats;
private int numberOfStandingSpots;
private int numberOfBoardingPassengers;
private int numberOfAlightingPassengers;
private int numberOfSeatedPassengers;
private int numberOfStandingPassengers;
private int numberOfDeclinedPassengers;
public static void main(String[] args){
Train train = new Train(150, 100);
train.stopAtStation(100, 0);
train.stopAtStation(75, 10);
System.out.println("After two stops:");
System.out.println(train.getNumberOfSeatedPassengers());
System.out.println(train.getNumberOfStandingPassengers());
train.stopAtStation(100, 0);
train.stopAtStation(100, 10);
System.out.println("After four stops:");
System.out.println(train.isFull());
System.out.println(train.getNumberOfSeatedPassengers());
System.out.println(train.getNumberOfStandingPassengers());
System.out.println(train.getNumberOfDeclinedPassengers());
train.stopAtStation(10, 50);
System.out.println("After five stops:");
System.out.println(train.isFull());
System.out.println(train.getNumberOfSeatedPassengers());
System.out.println(train.getNumberOfStandingPassengers());
System.out.println(train.getNumberOfDeclinedPassengers());
}
public Train(int numberOfSeats, int numberOfStandingSpots) {
for(int i = 0; i <= numberOfSeats; i++){
}
}
public void stopAtStation(int numberOfBoardingPassengers, int numberOfAlightingPassengers) {
}
public int getNumberOfSeatedPassengers() {
return numberOfSeatedPassengers;
}
public int getNumberOfStandingPassengers() {
return numberOfStandingPassengers;
}
public int getNumberOfDeclinedPassengers(){
return numberOfDeclinedPassengers;
}
public boolean isFull(){
int seated = getNumberOfSeatedPassengers();
int standing = getNumberOfStandingPassengers();
if(seated == 150 && standing == 100){
return true;
}
else{
return false;
}
}
}
and I am stuck at the for loop on how to make a loop such that it counts down the amount of seats, or up the amount of seated/ standing people

Blank return value( sum of two numbers)

public class Sum {
public static void main(String[] args) {
add(19, 21);
}
public static int add(int number1, int number2) {
int sum = number1 + number2;
return sum;
}
}
Why is not returning the value 40 from the sum and is there a better way to write this method.

I am trying to print the method findAverage in the main method, can anyone tell me how to fix

public class Grade {
private int [] array = {2,3,1,4,5,7,1};
public int findSum() {
int sum;
sum = 0;
for(int i =0; i <array.length; i++)
{
sum = sum +array[i];
}
return sum;
}
public double findAverage() {
double average;
average = findSum()/array.length;
return average;
}
}
class ExamClient {
public static void main(String[] args) {
double answer;
answer = findAverage();
System.out.println("Average of all elements in the array is" + answer);
}
}
In the main you have to create a instance of the class
Create instance
public static void main(String[] args)
{
double answer;
Grade g= new Grade();
answer = g.findAverage();
System.out.println("Average of all elements in the array is" + answer);
}
Also you can make the method static

get average value from a tree of nodes

I have to implement this method:
public int GetAverage(Node root){
//TODO implement
}
this method should get average value of all nodes of root tree. where :
public interface Node {
int getValue();
List<Node> getNodes();
}
do you have any ideas how to implement this method?
thank you
my attempt:
public static double value;
public static int count;
public static double getAverage(Node root) {
count++;
value += root.getValue();
for (Node node : root.getNodes()) {
getAverage(node);
}
return value / count;
}
but how to do it without the static fields outside of the method?
Simply traverse through all nodes and remember the count and the overall sum of all values. Then calculate the average. This is an example written in Java.
public interface INode {
int getValue();
List<INode> getNodes();
}
public class Node implements INode {
private List<INode> children = new ArrayList<INode>();
private int value;
#Override
public int getValue() {
return value;
}
#Override
public List<INode> getNodes() {
return children;
}
public static int getAverage(INode root) {
if (root == null)
return 0;
Counter c = new Counter();
calculateAverage(root, c);
return c.sum / c.count;
}
class Counter {
public int sum;
public int count;
}
private static void calculateAverage(INode root, Counter counter) {
if (root == null)
return;
counter.sum += root.getValue();
counter.count++;
// recursively through all children
for (INode child : root.getNodes())
calculateAverage(child, counter);
}
}
public static double getAverage(Node root) {
Pair p = new Pair(0,0);
algo(root, p);
return ((double) p.element1) / ((double) p.element2);
}
private static void algo(Node root, Pair acc) {
for(Node child : root.getNodes()) {
algo(child, acc);
}
acc.sum += root.getValue();
acc.nbNodes++;
}
With Pair defined as follows:
public class Pair {
public int sum;
public int nbNodes;
public Pair(int elt1, int elt2) {
this.sum = elt1;
this.nbNodes = elt2;
}
}

Question about LSD radix sort

I have the following code:
public class LSD{
public static int R=1<<8;
public static int bytesword=4;
public static void radixLSD(int a[],int l,int r){
int aux[]=new int[a.length];
for (int d=bytesword-1;d>=0;d--){
int i, j;
int count[]=new int[R+1];
for ( j=0;j<R;j++) count[j]=0;
for (i=l;i<=r;i++)
count[digit(a[i],d)+1]++;
for (j=1;j<R;j++)
count[j]+=count[j-1];
for (i=l;i<=r;i++)
aux[count[digit(a[i],d)]++]=a[i];
for (i=l;i<=r;i++)
a[i]=aux[i-1]; // <-- Line 19
}
}
public static void main(String[]args){
int a[]=new int[]{3,6,5,7,4,8,9};
radixLSD(a,0,a.length-1);
for (int i=0;i<a.length;i++){
System.out.println(a[i]);
}
}
public static int digit(int n,int d){
return (n>>d)&1;
}
}
At runtime it throws the following exception:
java.lang.ArrayIndexOutOfBoundsException: -1
at LSD.radixLSD(LSD.java:19)
at LSD.main(LSD.java:29)
Why is that happening?
I don't know enough about radix sort to know what your code should be, but why it's currently failing is pretty clear. You're calling radixLSD and passing 0 for l:
radixLSD(a,0,a.length-1);
When you get to this code:
for (i=l;i<=r;i++)
a[i]=aux[i-1];
In the first pass, i is set to l (0), and you try to do aux[i-1], or aux[-1], which is out of bounds

Resources