'How to sort a array with a function and using a code like this in java
Hello i have a java Code where i the Programm should sort the variable num but it only gives out some weird strings. I would like if you could help my with some tipps. The code needs to give out 1,4,6,9 i hope everyone understands what's about.
public class A3 {
public static void meinefunktion(int[] num, int temp, int i, int j) {
if (num[j] < num[i]) {
temp = num[i];
num[i] = num[j];
num[j] = temp;
}
}
public static void main(String[] args) {
int[] num = { 4, 9, 6, 1 };
int temp;
temp = 0;
int i = 0;
while (i < num.length) {
int j = i + 1;
while (j < num.length) {
meinefunktion(num, temp, i, j);
j += 1;
}
i += 1;
}
System.out.println(num);
}
}
Solution 1:[1]
You can do it in the main function as bellow :
public static void main(String[] args) {
int[] num = { 4, 9, 6, 1 };
Arrays.sort(num);
for (int j : num){
System.out.println(j);
}
}
Solution 2:[2]
You are printing the array directly which, in Java, doesn't print the single elements, but a generated reference string. Generally, you can convert arrays into a List
object which overrides its toString
method, properly. Depending on your version of Java there are the following options:
java.util.Arrays.toList(...)
or:
java.util.List.of(...)
Unfortunately, this doesn't work for primitive array component types (such as int
). You need to use the boxed type Integer
:
package com.yaypay;
import java.util.Arrays;
public class AaaTest {
public static void meinefunktion(Integer[] num, int i, int j) {
if (num[j] < num[i]) {
int temp = num[i];
num[i] = num[j];
num[j] = temp;
}
}
public static void main(String[] args) {
Integer[] num = { 4, 9, 6, 1 };
int i = 0;
while (i < num.length) {
int j = i + 1;
while (j < num.length) {
meinefunktion(num, i, j);
j += 1;
}
i += 1;
}
System.out.println(Arrays.asList(num));
}
}
Solution 3:[3]
Yes, your code does exactly what you need! The only minor missing point is the printing statement - System.out.println(num). Instead of it, you may please loop over the array to print the results as shown below. This sample code uses while loop since you already know it.
int index = 0;
while (index < num.length) {
System.out.println(num[index]);
index++;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | FRS |
Solution 2 | PAX |
Solution 3 |