snippetjavaMinor
Plain old quick sort
Viewed 0 times
sortoldplainquick
Problem
Any suggestions for improvement are welcome.
public static int[] concatArrays(int[] a1, int[] a2) {
int n1 = a1.length;
int n2 = a2.length;
if(n1 == 0) return a2;
if(n2 == 0) return a1;
int n = n1 + n2;
int counter = 0;
int[] result = new int[n];
for(; counter < n1; counter++) {
result[counter] = a1[counter];
}
for(; counter < n; counter++) {
result[counter] = a2[counter - n1];
}
return result;
}
public static int[] concatArrays(int[] a1, int a2) {
int[] a2New = new int[] {a2};
return concatArrays(a1, a2New);
}
public static int[] sort(int[] data) {
if(data.length == 0) return new int[0];
int nBefore = 0;
int nAfter = 0;
int[] beforeArray = new int[data.length];
int[] afterArray = new int[data.length];
for(int i = 1; i < data.length; i++) {
if(data[i] < data[0]) {
beforeArray[nBefore++] = data[i];
}
else {
afterArray[nAfter++] = data[i];
}
}
int[] beforeArrayTrimmed = new int[nBefore];
int[] afterArrayTrimmed = new int[nAfter];
System.arraycopy(beforeArray, 0, beforeArrayTrimmed, 0, nBefore);
System.arraycopy(afterArray, 0, afterArrayTrimmed, 0, nAfter);
return concatArrays(
concatArrays(sort(beforeArrayTrimmed), data[0]),
sort(afterArrayTrimmed)
);
}Solution
Using
This way, the for loop looks just like people expect it to look. Your implementation requires extra thought. There is still a single arithmetic operation for indexing in the second loop, so reusing
One line if statements can be missed by someone reading your code. Plus you need to remember to add curly brackets if you want to add a second line.
counter for both for loops seems awkward.for(int i = 0; i < n1; i++) {
result[i] = a1[i];
}
for(int i = 0; i < n2; i++) {
result[n1 + i] = a2[i];
}This way, the for loop looks just like people expect it to look. Your implementation requires extra thought. There is still a single arithmetic operation for indexing in the second loop, so reusing
counter is not saving you anything.One line if statements can be missed by someone reading your code. Plus you need to remember to add curly brackets if you want to add a second line.
concatArrays(int[] a1, int a2) does not concatenate arrays. Function names that lie about what they do are bad.Code Snippets
for(int i = 0; i < n1; i++) {
result[i] = a1[i];
}
for(int i = 0; i < n2; i++) {
result[n1 + i] = a2[i];
}Context
StackExchange Code Review Q#78808, answer score: 4
Revisions (0)
No revisions yet.