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;
}
}
}
Related
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.
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);
I have to do an Array List for an insertion sort and my teacher sent this back to me and gave me an F, but says I can make it up before Friday.
I do not understand why this isn't an A.L insertion sort.
Can someone help me fix this so it hits his criteria?
Thanks.
HE SAID:
After checking your first insertion sort you all did it incorrectly. I specifically said to shift the numbers and move the number into its proper place and NOT SWAP THE NUMBER INTO PLACE. In the assignment in MySA I said if you do this you will get a 0 for the assignment.
import java.util.ArrayList;
public class AListINSSORT {
private static void insertionSort(ArrayList<Integer> arr) {
insertionSort();
}
private static void insertionSort() {
ArrayList<Integer> swap = new ArrayList<Integer>();
swap.add(1);
swap.add(2);
swap.add(3);
swap.add(4);
swap.add(5);
int prior = 0;
int latter = 0;
for (int i = 2; i <= latter; i++)
{
for (int k = i; k > prior && (swap.get(k - 1) < swap.get(k - 2)); k--)
{
Integer temp = swap.get(k - 2);
swap.set(k - 2, swap.get(k - 1));
swap.set(k - 1, temp);
}
}
System.out.println(swap);
}
}
First of all, it seems your teacher asked you to use a LinkedList instead of an ArrayList. There is quite a difference between them.
Secondly, and maybe more to the point. In your inner loop you are saving a temp variable and swapping the elements at position k - 2 and k - 1 with each other. From the commentary this is not what your teacher intended. Since he wants you to solve the problem with element insertion, I recommend you look at the following method definition of LinkedList.add(int i, E e): https://docs.oracle.com/javase/7/docs/api/java/util/LinkedList.html#add(int,%20E).
This should point you in the right direction.
As far as I see, your code does nothing at all.
The condition of the outer for loop
for (int i = 2; i <= latter; i++)
is not fulfilled.
As you start with i = 2 and as latter = 0, it never holds i <= latter.
Thus, you never run through the outer for loop and finally just give back the input values.
If you add the input values to swap in a different order (not already ordered), you will see that your code does not re-order them.
There's a lot of stuff wrong here.
Firstly, your method:
private static void insertionSort(ArrayList<Integer> arr) {
insertionSort();
}
takes an ArrayList and completely ignores it. This should presumably be the List which requires sorting.
Then in insertionSort() you create a new ArrayList, insert some numbers already in order, and then attempt something which looks nothing like insertion sort, but slightly more like bubble sort.
So, when you call insertionSort(List) it won't actually do anything to the list at all, all the work in insertionSort() happens to a completely different List!
Since on SO we don't generally do people's homework for them, I suggest looking at the nice little animated diagram on this page
What you should have then is something like:
public void insertionSort(LinkedList<Integer> numbers) {
//do stuff with numbers, using get() and add()
}
My code is not working properly. It is bubble sorting in Java. I know I can get any code from google but I think it is not good to me and google would not tell my why my code is not working.
Here is the code:
int temp=0;
int x=10;
int [] array = new int [x];
for(int i=0;i<array.length-1;i++){
array[i]=i;
//System.out.println(array[i]);
if(array[i]>array[i+1]){
temp=array[i+1];
array[i+1]=array[i];
array[i]=temp;
}
System.out.println(array[i]);
}
}
}
As you're not populating your input array all of its values will be 0 - as such the resulting sorted array will contain all 0s
Additionally, you're overwriting your input array at
array[i]=i;
Which means you'll be modifying the array in a way that bubble sort does not do.
(I'm trying not to give the full answer as I assume you want to do get this working yourself)
Can someone please help me how to solve it?
Create a new class named blabla in the bla package. An instance of the class should
be able to store a two-dimensional array of type double. The size of the array is not
bound. The class should have a no-parameter procedure-like method named sortRows. The
method should sort rows of the array in the following manner: the values of the last
column must be in a descending order (greatest first, smallest last).
So i tried to do myself, please help me if there is a mistake.
double temp = 0;
double[][] number;
boolean fixed=false;
while(fixed==false){
fixed=true;
}
number = new double[5][5];
for(int i=0; i<number.length-1; i++){
if(number[i][i] > number[i+1][i+1])
temp = number[i+1][i+1];
number[i+1][i+1] = number[i][i];
number[i][i]=temp;
fixed=false;
}
for(int i=0; i<number.length; i++){
System.out.println(number[i][i]);
}
Well, I'm not gonna do your homework!
You should be able to create a class in a package yourself,
For creating dynamic arrays, check this topic: Variable length (Dynamic) Arrays in Java
For sorting arrays, check this topic: char multidimensional array sorting in java
This should get you going, I hope ;)