Descending Selection Sort - java

I have wrote a selection sort method to descend the numbers of the array. The header of the method is:
public static void selectionSort(int[] num) { ... }
In the main class, I prompted the user to enter he size of the array and the numbers inside the array, but I ran into compiler error that it didn't except how I wrote the method with the array in the main class.
int sorted = selectionSort(arrayNum[arraySize]);
System.out.println("Sorted numbers of the array are: " + sorted);
I know there is a problem because of the int sorted isn't the same with the array int[] arrayNum, and there is a problem with my usage of the method.
What is the correct way to write the array of the main class in that method?

The working code in this online compiler ide.
The basic issue is, the selection sort implantation you probably implemented or took from book is implanted in a typical way where the the sort method modifes the input array.
So just pass the array, the array will not contain the sorted elements.
Note: in the example, I have just used the existing sorting method that sorts ascending order. Fix that method with your implementation.
int[] num = { 4, 8,2,1,6};
selectionSort(num);
System.out.println(Arrays.toString(num));
https://www.codiva.io/p/be4128fd-3a65-4b1a-8bb0-721fa5107369

Related

Process multi dimensional arrays in Java

What is the best way to take in a multi dimensional array as a method parameter in the form of an object and then reconstruct it as a variable inside that method? The reason I want to pass the array in as an object is because I want my code to be able to use any n dimensional array. I could circumvent this by using method overloading but making hundreds of identical methods just to account for all possible array dimensions seems like a very bad way to do it. However, using an object as a parameter causes a new set of challenges since I have no way to initialize that array since you normally need to explicitly declare an arrays dimensions. Based on some of my research I have figured out a way to determine the dimensions of an array passed in as an object which you can view in the following code snippet.
public static void callTestArray() {
var matrix = new int[][]{{1,2}, {4, 6, 7}};
test(matrix);
}
public static void test(Object obj) {
final int dimensions = dimensionOf(obj);
System.out.println("Dimensions:" + dimensions);
//I can't create a variable from this though since I need to hard code the dimensions of the array
}
/**
* This returns the amount of dimensions an array has.
*/
public static int dimensionOf(Object arr) {
int dimensionCount = 0;
Class<?> c = arr.getClass(); // getting the runtime class of an object
while (c.isArray()) { // check whether the object is an array
c = c.getComponentType(); // returns the class denoting the component type of the array
dimensionCount++;
}
return dimensionCount;
}
I have been looking around for a while now but I cant find an object that allows me to pass in any n dimensional array in that allows me to easily access all of an arrays typical information? Was this not included in Java or am I just missing it? That being said since 255 is the max amount of dimensions an array can have I could make my own utils class to handle this but it would require a ton of redundancies and effort to handle all cases. I just want to make sure it has not already been made before I waste hours making something like that. Also if anyone has a better way of doing it with any internal java libraries please let me know!
Instead of passing around arrays we more often than not use collections like ArrayList, this allows us some abstraction and allows us to add some common methods to it. Note that ArrayList doesn't extend arrays, it simply implements a list interface.
I recommend the same thing for you, instead of passing around an array, consider encapsulating the array in a class and pass that class around. Use the class to do certain simplifications, for instance you might have a method allowing it to apply a function to each element of the matrix or one to resize the matrix.
You might track your matrix's dimensions in different variables allowing you to resize it without re-allocating the array (like an ArrayList does)
Another advantage of the encapsulation, if you wish to do something different like make a sparse matrix out of it, you could re-implement the underlying code without changing the ways it's used (Like the way ArrayList and LinkedList have the same interface but do things different ways for different use cases)
Your other conditions seem to work for this Matrix object as well as it would arrays, for instance you would pass dimensions into the constructor to create it initially (Although, as I said, you could easily expand it later, especially if you used an ArrayList of ArrayLists for your underlying implementation, if you needed that)
I think the reason it's not included in Java is that it is not very commonly used and quite easy to implement, but if you really don't want to do it yourself, apache has a Matrix implementaiton that looks like it will fit.
We use time series data like hourly tempatures a lot (Often down to 10 second resolution for a day) and so we built our own class that essentially represents a line on a graph with the y axis of "Date", like a linked list but each value is timestamped. This structure is AMAZINGLY useful for us and I often wonder why it's not in Java, but I think I just answered my own question, not used enough.
This is a job for varargs:
public static void main(String[] args) {
var matrix = new int[][]{{1,2}, {4, 6, 7}};
System.out.println("Length is: " + getSize(matrix));
}
public static int getSize(int[]... multiArray) {
return multiArray.length;
}
which prints out:
Length is: 2
Also, unless you have to use an array to hold your int arrays, I would use an ArrayList<int[]> instead. That way you can easily add to your list like:
ArrayList<int[]> multiArray = new ArrayList<>();
multiArray.add(new int[]{1,2,3});
multiArray.add(new int[]{4,5,6});
and then you can get its size by simply calling:
multiArray.size()
Here's my attempt. You use Object as the parameter and then check for the array dimension in the body of the method. In this example, I only limit it to 3D array but you can go up to any dimension.
public class Main{
static void process(Object o){
if (o instanceof int[]){
int[] a = (int[]) o;
System.out.println("1D. length is " + a.length);
} else if (o instanceof int[][]){
int[][] a = (int[][]) o;
System.out.println("2D. row=" + a.length + ", col=" + a[0].length);
} else if (o instanceof int[][][]){
int[][][] a = (int[][][]) o;
System.out.println("3D. row=" + a.length + ", col=" + a[0].length + ", depth=" + a[0][0].length);
} else {
System.out.println("Unsupported array dimension.");
}
}
public static void main(String[] args) {
int[] a = {1,2,3};
int[][] b = {{1,2,3},{1,2,3}};
int[][][] c = {
{ {1,2,3}, {1,2,3} },
{ {1,2,3}, {1,2,3} }
};
process(a);
process(b);
process(c);
}
}
Output:
1D. length is 3
2D. row=2, col=3
3D. row=2, col=2, depth=3

Sort a List of objects by one of it`s fields (that contains list of Strings)

I have a List of objects. Inside it I have another List of Strings (that contains numbers).
How can I order the List of objects, by the the numbers, that inside the List of Strings?
I tried to do something like that:
Collections.sort(bets, new Comparator<Bet>() {
public int compare(Bet b1, Bet b2) {
return Integer.valueOf(b1.getPlayersHighScores().get(0))
.compareTo(Integer.valueOf(b2.getPlayersHighScores().get(0)));
}
});
Collections.reverse(bets);
The main problem is that the List of bets may have one or more bets, but the List of getPlayersHighScores can contain many Strings.
First of all, why is the highscore a String if it contain a Number? Wouldn't it make more sense to make it Integer or some other Number?
Second, why do you keep a list of highscores? Doesn't it make more sense to retain only one highscore (the highest)?
Thirdly, by what property of the List of highscores would you order the Bets? As you've observed, just taking the first highscore for each bet doesn't make much sense. Would you want to order them by the max of each list? The sum? The avg?
Say you're going with sum, you then would only have to write you comparator something like (Java8):
new Comparator<Bet>() {
public int compare(Bet b1, Bet b2) {
return b1.getPlayersHighScores().stream().mapToInt(Integer::valueOf).sum()
.compareTo(b2.getPlayersHighScores()stream().mapToInt(Integer::valueOf).sum());
}
}

Cannot invoke indexOf on an Array of strings?

I'm writing a method to calculate the distance between 2 towns in a given array by adding all the entries between the indexes of the two towns in the second array, but I can't invoke indexOf on the first array to determine where the addition should start. Eclipse is giving me the error "Cannot invoke indexOf on array type String[]" which seems pretty straight forward, but I do not understand why that won't work.
Please note the program is definitely not complete.
public class Exercise_3 {
public static void main(String[] args){
//Sets the array
String [] towns={"Halifax","Enfield","Elmsdale","Truro","Springfield","Sackville","Moncton"};
int[] distances={25,5,75,40,145,55,0};
distance(towns, distances, "Enfield","Truro");
}
public static int distance(String[] towns,int[] distances, String word1, String word2){
int distance=0;
//Loop checks to see if the towns are in the array
for(int i=0; i<towns.length; i++){
if(word1!=towns[i] || word2!=towns[i] ){
distance=-1;
}
//Loop is executed if the towns are in the array, this loop should return the distance
else{
for(int j=0; j<towns.length; j++){
*int distance1=towns.indexOf(word1);*
}
}
}
return distance;
}
}
No, arrays do not have any methods you can invoke. If you want to find the index of an given element, you can replace String[] by ArrayList<String>, which has an indexOf method to find elements.
It doesn't work because Java is not JavaScript.
The latter offers an array prototype that actually exposes the function indexOf, while the former does not.
Arrays in JavaScript are completely different from their counterparts in Java.
Anyway, you can be interested in the ArrayList class in Java (see here for further details) that is more similar to what you are looking for.
How about this (from this post)?
There are a couple of ways to accomplish this using the Arrays utility class.
If the array is not sorted:
java.util.Arrays.asList(theArray).indexOf(o)
If the array is sorted, you can make use of a binary search for performance:
java.util.Arrays.binarySearch(theArray, o)
I hope this helps you. If it doesn't, please downvote.

Method cannot access the sorted array

The following code sorts through a dictionary of words in lexicographical order. The problem is that I cannot access the sorted array outside of the for loop. Well I think this is the problem. I have declared the array words in another method and returned it to a private variable within the same class. But after I sort the array and try to print it out, it just prints out the original array. I also want to mention that this sorting method does work as I have tested it in another class where everything was in the main method. So again I believe my problem has to do with returning the new sorted array. I also need to write a few lines of code within the method after the array is sorted and when I tried to return the array, using "return words;" I was unable to write this code.
public void insertionSort() {
int in, out;
for (out=1; out<nElems; out++){
String temp = words[out]; // remove marked item
in = out; // start shifting at out
while (in>0 && words[in-1].compareTo(temp)>0){ // until temp is lexicographically after after the word it is being compared to
words[in] = words[in-1]; // shifts word to next position in lexicographical order
--in;
}
words[in] = temp;
}
for(int i=0; i <words.length; i++)
System.out.println(words[i]);
I have declared the array words in another method
It sounds like you have declared two arrays: one inside the other method and an entirely separate one at class level that is being sorted. Make sure both methods are using the same array.
If you want them both to use the array declared at class level, don't declare a separate array in the other method. E.g., if you have String[] words = new String[10]; in the other method, change it to words = new String[10];. If you really need the nElems variable (i.e., if the sort method can't simply use words.length), make sure that variable is also not being redeclared and is being set to the correct value.
Alternatively, instead of depending on putting the data to be sorted in a particular array, your sort method would be more generally useful if it accepted any array to be sorted as a parameter:
public static void insertionSort(String[] words, int nElems) {
/* ... rest of method as before ... */
}
I've made that method static too, since it no longer depends on any instance fields.
Well, as I understand what you are saying, you are using a private variable at class level and that variable receives the words[] array items from a method... in that case:
Make sure the private variable at class level is an array named words.
Make the private variable (now named words) the same type as the words array received from the other method.
Because you are calling words from insertionSort() you need to acces the private variable values, you can't get the words[] array values from the other method, because that array is local to that method, so you must return it's values to some array varibale (the private variable that you must name words), so it's that variable that you must access.

array-element:array-name in Java

Below is an example program from some notes on how to use the for loop in Java. I don't understand how the line element:arrayname works. Can someone briefly explain it, or provide a link to a page that does?
public class foreachloop {
public static void main (String [] args) {
int [] smallprimes= new int [3];
smallprimes[0]=2;
smallprimes[1]=3;
smallprimes[2]=5;
// for each loop
for (int element:smallprimes) {
System.out.println("smallprimes="+element);
}
}
}
It's another way to say: for each element in the array smallprimes.
It's equivalent to
for (int i=0; i< smallprimes.length; i++)
{
int element=smallprimes[i];
System.out.println("smallprimes="+element);
}
This is the so called enhanced for statement. It iterates over smallprimes and it turn assignes each element to the variable element.
See the Java Tutorial for details.
for(declaration : expression)
The two pieces of the for statement are:
declaration The newly declared block variable, of a type compatible with
the elements of the array you are accessing. This variable will be available
within the for block, and its value will be the same as the current array
element.
expression This must evaluate to the array you want to loop through.
This could be an array variable or a method call that returns an array. The
array can be any type: primitives, objects, even arrays of arrays.
That is not a constructor. for (int i : smallPrimes) declares an int i variable, scoped in the for loop.
The i variable is updated at the beginning of each iteration with a value from the array.
Since there are not constructors in your code snippet it seems you are confused with terminology.
There is public static method main() here. This method is an entry point to any java program. It is called by JVM on startup.
The first line creates 3 elements int array smallprimes. This actually allocates memory for 3 sequential int values. Then you put values to those array elements. Then you iterate over the array using for operator (not function!) and print the array elements.

Categories

Resources