'Java Array Odd Sorting Algorythm
I got an algorithm to write that set order of an Arrey but in a specific way.
- Find the lowest number of an array
- Save it at the start of the new array.
- Mark in the origin (starting) array spot which from we found the lowest number (mark by for example change it to maximum int number).
- Go back to point 1.
- Repeat all to rewrite all numbers in ascending order.
So I got a working code that changes the order, but I can't figure out how to mark the numbers, and thanks to this create a new array.
public static void arrOrder(int[] intArray){
int temp = 0;
for (int i = 0; i <intArray.length; i++) {
for (int j = i+1; j <intArray.length; j++) {
if(intArray[i] >intArray[j]) {
temp = intArray[i];
intArray[i] = intArray[j];
intArray[j] = temp;
}
}
}
}
Solution 1:[1]
So I got a working code that changes the order
No, you don't. Even if you figure out how to do the marking thing, the code you pasted changes the order, perhaps, but it doesn't sort anything.
Your code will, for each element (the i loop):
For each element above it, if it is higher, replace stuff. This isn't, at all, what you wanted - what you wanted is to first figure out if the i-th number is the smallest number. If no, do nothing (continue on to the next number, check if that one is lowest), If yes, write it into a new array, and replace it with some placeholder to indicate that you've already done that one - the suggestion is Integer.MAX_VALUE, a fine suggestion.
The 'strategy' you describe involves:
- Making a separate new array of the right size.
- Maintaining a variable that counts how many numbers have been written into this new array - when you find your next lowest number, you'd write it at that index.
- A double-loop construct where the inner loop doesn't write anything, it merely tracks if the
inumber is the lowest. - Some code inside the
iloop but after thejloop that acts only ifiwas, in fact, the lowest number. Presumably involves a boolean that you set initially and clear in the inner loop (thejloop), then anifthat only acts if the boolean remains true, i.e. - no lower number exists. - The
jloop needs to hit the entire array, not 'only stuff above you'. - You need to explicitly exclude your sentinel value. I suggest you use
Integer.MAX_VALUE. This probably involves anotherif.
If you code looks anything like what you pasted, you didn't do it right, given that what you pasted doesn't do any of the named strategy elements.
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 | rzwitserloot |
