I need to do the following: I was given an array with random integers. My task now is to sort the array so that the smallest int comes first and the greatest int at the end of the array. I need to do this by using a rather strange method: As long as the array isn't sorted, take two different random positions in the array and swap them. I then need to print out how many times it swapped two positions. So I've tried to implement that but I doesn't seem to work:
int[] values = new int[] { 50, 10, 20, 4, 5, 1, 5 };
int steps = randomSort(values);
public static int randomSort(int[] values) {
int steps = 0;
Random r = new Random();
int l = values.length;
sorted = checkIfSorted(values);
if(sorted = true) {
return steps;
}
// sort the array
while(sorted = false) {
int v = 0;
int x = r.nextInt(l);
int y = r.nextInt(l);
while(x == y) {
y = r.nextInt(l);
}
v = values[x];
values[x] = values[y];
values[y] = v;
sorted = checkIfSorted(values);
steps = steps + 1;
}
return steps;
}
public static boolean checkIfSorted(int[] values) {
for(int i = 0; i < values.length; i++) {
if(values[i] > values[i+1]) {
return false;
}
}
return true;
}
I'm fairly new to Java programming, so I might have made some stupid mistakes xD
Aucun commentaire:
Enregistrer un commentaire