Java Bucket Sort of Elements in another Array - java

I just recently started learning java and today I learned how I can do the so called selection sort. I have been trying for the last 3 hours to do a bucket sort, but there are some parts which I don't know how to code. Important : I am learning java completely by myself with a book. I am not a student and I am doing this as a hobby. I already googled everything I could think of and I didn't find a solution. I don't have a teacher or anybody who I can ask, so yea, any help would be appreciated!
Code:
private int[] bucketSort() {
int[]bucket=new int[maxSize+1];
int[]sortedElements = new int[elementaros.length];
for(int i=0; i<elementaros.length;i++) {
bucket[elementaros[i]]++; //it says that I can't convert from Car to int. How can I add the elements of array elemenators to bucket?
}
int outPos = 0;
for (int j = 0; j < bucket.length; j++){
for (int k = 0; k < bucket[i]; k++){
sortedElements[outPos++] = i;
}
}
return bucket;
}
The idea of the code :
I have an array elements of type Car(Car is another class of my program). It looks like this - Car[] elementaros. int maxSize shows the maximum number of administrable Car objects. What I want to do is the following - I want to sort the elements in the elementaros array alphabetically. I would really really appreciate it if somebody has the time to show me how this would function with an example code or would just give me some tips. As I said - I have nobody who I can ask.

A selection sort is a combination of searching and sorting.
The principle is quite simple but I always prefer a diagram than huge explanations.
Start a pointer at the beginning of your unsorted array. Then, for each value of the array, search for the minimum value (or search for the alphabeticaly ordered car) in your array and switch the position of the founded Car with the pointer (which is a Car too)
Then you can advance the pointer to the next element of the array.
Here is a basic implementation to do this
public static Car[] doSelectionSort(Car[] elementaros) {
for (int i = 0; i < elementaros.length - 1; i++) {
int index = i;
for (int j = i + 1; j < elementaros.length; j++) {
if (elementaros[j].getName().compareTo(elementaros[index].getName()) < 0) {
index = j;
}
}
Car nextOrderedCar = elementaros[index];
elementaros[index] = elementaros[i];
elementaros[i] = nextOrderedCar;
}
return elementaros;
}
Just for example sake, I imagine your object of type Car has a name that we could use for the comparison.
UPDATE 1:
I have read your initial question too quickly and it leds me to answer a total different sorting algorithm. My bad.
I found an implementation here that does the trick:
williamfiset bucket sort
explanation of bucket sort plus different implementation
Hope this helps.

Related

Sorting arrays by order

I am currently starting to learn java for school and for myself and I am stuck on a question I can't answer...
The problem contains two arrays including different ints with different length.
Both arrays should have the same order of numbers when they are included in the array.
For Examples {3,8,2,6} and {3,2,6}
How can I make sure that the arrays are sorted in the same way?
I don't want a sort method form lowest to highest, just the same order?
The algorithm should be based on normale if/ while/ for methods.
Appreciate the help!
I think a code like below should solve your need. Finally, c will have elements of b ordered same as a. Hope this helps you. Still I don't understand the use of this.
Regards, Srikanth Kondaveti
int a[] = { 3,8,2,6};
int b[] = {6,3,2};
int c[] = new int[b.length];
int index = 0;
for(int k=0; k<a.length; k++) {
for(int l=0; l<b.length; l++) {
if(a[k]==b[l]) {
c[index++]=b[l];
break;
}
}
}

Where is the Data Changing? - Permutations in Java

So for this extra credit problem in my calculus class, my other nerdy classmates and I decided that we would build a program to brute force a solution. One of these steps involves permutations. Through this algorithm, I managed to get it to work (I think):
public void genPermutations(int[] list, int k){
System.out.println("List: " + Arrays.toString(list));
System.out.println("----------------------");
if(k > list.length){
System.out.println("Not enough elements!");
return;
}
int[] counts = new int[list.length];
for(int i = 0; i < counts.length; i++){
counts[i] = 1;
}
int[] data = new int[k];
permutationHelper(list, counts, data, 0, k);
}
public void permutationHelper(int[] list, int[] counts, int[] data, int index, int k){
if(index == k){
//System.out.println(Arrays.toString(data));
permutations.add(data);
}else{
for(int i = 0; i < list.length; i++){
if(counts[i] == 0){
continue;
}
data[index] = list[i];
counts[i]--;
permutationHelper(list, counts, data, index + 1, k);
counts[i]++;
}
}
}
I have an ArrayList that stores all of the possible permutations (as integer arrays) that can be made from k elements of the list that I pass into the function. The problem is that if I print all of these permutations outside of the function, say after I call the genPermutations function, every permutation now is the same. But, when I print out the data where the comment is in the permutationHelper function, it correctly lists every possible permutation; I'm just unable to access them within the program later. My question is why are the values changing when I exit the function? Any help would be greatly appreciated.
Here are some pictures:
What is printed where the comment is.
What is printed later in the program.
The code used to print everything outside of the function is:
for(int i = 0; i < permutations.size(); i++){
System.out.println(Arrays.toString(permutations.get(i)));
}
I don't really know if that's necessary to know, but I just thought I'd include it just in case. Thanks in advance.
You're constantly modifying the same array object. Instead of adding different arrays to your list, you're in fact adding a reference to the same array over and over again.
To fix, instead of adding the data array to your list, you would have to add a copy of it, e.g. using Arrays.copyOf():
permutations.add(Arrays.copyOf(data, data.length));
Here the problem is that you are modifying the array after adding it to the list, you are modifying the same object again and again in different iterations. You were getting [3,2,1] in the list is because that was the outcome from last iteration. So as a fix you can use the following code. What it does is it will create a copy of data array and add that to the list.
int[] temp = Arrays.copyOf(data, data.length);
permutations.add(temp);
OR you can use clone() from array as follows.
int[] temp = data.clone();
permutations.add(temp);

2 dimensional array & method calls - beginner

I'm currently working on a homework assignment for a beginner-level class and I need help building a program that tests if a sodoku solution presented as an int[][] is valid. I do this by creating helper methods that check both rows, columns and grids.
To check the column I call a method called getColumn that returns a column[]. When I test it out it works fine. I then pass it out on a method called uniqueEntries that makes sure that there are no duplicates.
Problem is, when I call my getColumn method, it returns an array consisting of only one number (for example 11111111, 22222222, 33333333). I have no idea why it does that. Here is my code:
int[][] sodokuColumns = new int[length][length];
for(int k = 0 ; k < sodokuPuzzle.length ; k++) {
sodokuColumns[k] = getColumn(sodokuPuzzle, k);
}
for (int l = 0; l < sodokuPuzzle.length; l++) {
if(uniqueEntries(sodokuColumns[l]) == false) {
columnStatus = false;
}
}
my helper is as follows
public static int[] getColumn(int[][] intArray, int index) {
int[] column = new int[intArray.length];
for(int i = 0 ; i < intArray.length ; i++) {
column[i] = intArray[i][index];
}
return column;
}
Thanks !
You said:
when I call my getColumn method, it returns an array consisting of only one number (for example 11111111, 22222222, 33333333).
I don't see any issue with your getColumn method other than the fact it's not even needed because getColumn(sodokuPuzzle, k) is the same as sodokuPuzzle[k]. If you're going to conceptualize your 2D array in such a way that your first index is the column then for your purpose of checking uniqueness you only need to write a method to get rows.
The issue you're having would seem to be with another part of your code that you did not share. I suspect there's a bug in the logic that accepts user input and that it's populating the puzzle incorrectly.
Lastly a tip for checking uniqueness (if you're allowed to use it) would be to create a Set of some kind (e.g. HashSet) and add all of your items (in your case integers) to that set. If the set has the same size as your original array of items then the items are all unique, if the size differs there are duplicates.

ArrayList Retrieve First and Last Result without Sorting ArrayList

I have an ArrayList of String, and I would like to retrieve the first and last result of the names after calculating the order of alphabets. Below is my code snippet:
ArrayList<String> list = new ArrayList<String>(20);
list.add("Charles Darwin");
list.add("Albert Einstein");
list.add("Issac Newton");
list.add("Tony Hoare");
list.add("Grace Hopper");
list.add("Edgar Dijkstra");
list.add("Ada Lovelace");
list.add("Charles Babbage");
list.add("Stephen Hawking");
String biggest = "";
String smallest = "";
for (int i = 0; i < list.size(); i++) {
String first = list.get(i);
for (int j = 0; j < list.size(); j++) {
String second = list.get(j);
if (!first.equalsIgnoreCase(second)) {
if (first.compareToIgnoreCase(second)>0){
biggest=first;
}
if (first.compareToIgnoreCase(second)<0){
smallest=first;
}
}
}
}
System.out.println(biggest);
System.out.println(smallest);
I am able to retrieve every value for comparison, however, the results are always showing Stephen Hawking as the biggest and smallest.
My desired results are Ada Lovelace as biggest and Tony Hoare as smallest.
You can use Collections.min / max
Your conditional statements seem to wrong.
if (first.compareToIgnoreCase(second)>0){
biggest=first;
}
if (first.compareToIgnoreCase(second)<0){
smallest=first;
}
You're comparing the element in the outer loop to the element in the inner loop. You never make a comparison against the biggest and smallest.
This should help you find the biggest and smallest String in your list.
String biggest = list.get(0);
String smallest = list.get(0);
for (int i = 1; i < list.size(); i++) {
if(list.get(i).compareToIgnoreCase(biggest) > 0)
biggest = list.get(i);
if(list.get(i).compareToIgnoreCase(smallest) < 0)
smallest = list.get(i);
}
Alternatively, you can use Collections.min() and max() as stated in one of the other answers.
are your required to use List ? You might want to see http://docs.oracle.com/javase/7/docs/api/java/util/SortedSet.html. then you can use first() and last() method
I'm new to Java, but I can still recognize multiple issues with this code:
Why are you hard coding initial capacity to 20?
Why are you using indexed loops instead of for each?
Why are you using a nested loop to find min/max?
Use else instead of running the same comparison twice
If first always equals second biggest and smallest will remain uninitiated
And last, and directly dressing your question, all your code does is finding if the last item is greater & smaller than any of the other items in the list, not all of them, since you keep ignoring previous findings and not using biggest/smallest as a condition in any of your comparisons.

Using Strings to Call Methods in Java

This is one of the first programs I am writing by myself. I want to make a physics calculator where many objects can interact with each other and give the user an option to add more objects. My idea is to have a for loop that runs through each object pulling on each other like this.
for(int n=1; n<=totalObjs; n++){
objName = "object"+n;
for(int i=1; i<n; i++){
obj2Name = "object"+i
objName.getMass();
//getting mass and position from both
//calculations here}
for(int x=n+1; x<=totalObjs; x++){
//same stuff as in the previous for loop}
}
I know there are probably huge syntax errors or logical errors in that but I'd like to sort through those on my own. Is there some way i could reference objects with the strings?
Is there some way i could reference objects with the strings?
Yes, via a Map<String, SomeType> such as a HashMap<String, SomeType>.
Think of this as being similar to an array or ArrayList, but instead of using number indices, you'd be using String indices.
Now looking at your code however, you might be better off using a simple ArrayList or array, since you appear to be trying to use numeric indices.
e.g.,
// assume a class called GravMass which has Mass, position, and momentum
List<GravMass> gravMassList = new ArrayList<GravMass>();
// fill your list
for(int i = 0; i < gravMassList.size() - 1; i++) {
GravMass gravMass1 = gravMassList.get(i);
int mass1 = gravMass1.getMass();
for(int j = i + 1; j < gravMassList.size(); j++){
GravMass gravMass2 = gravMassList.get(j);
int mass2 = gravMass2.getMass();
//getting mass and position from both
//calculations here}
}
}

Categories