Good evening,
something quirky is going on with Java. I'll be the first to admit that I suck at Java, but I really can't wrap my head around this one, maybe someone can help.
I'm trying to make a class to execute GnomeSort (some niche sorting method, just to practice with Java).
Here's what I've build...
package sorting;
import org.testng.annotations.Test;
import java.util.ArrayList;
import java.util.Arrays;
import static org.testng.internal.junit.ArrayAsserts.assertArrayEquals;
public class GnomeSort<T extends Comparable<? super T>> {
public static void main(String[] args) {}
public static T[] gnomeSort(T[] arrayToSort) {
for (int i = 0; i < arrayToSort.length; i++) {
T current = arrayToSort[i];
T next = arrayToSort[i + 1];
if (current.compareTo(next) > 0) {
current = arrayToSort[i + 1];
next = arrayToSort[i];
}
}
return arrayToSort;
}
static ArrayList<Character> sample = new ArrayList<Character>(
Arrays.asList('t', 'f', 'a', 'b', 'u', 'd', 'g', 'c'));
@Test
public void testGnomeSort() {
Character[] processed = {'t', 'f', 'a', 'b', 'u', 'd', 'g', 'c'};
Character[] ordered = {'a', 'b', 'c', 'd', 'f', 'g', 't', 'u'};
GnomeSort.gnomeSort(processed);
assertArrayEquals(processed, ordered);
}
}
the gnomeSort method, for some reason is giving the error:
'sorting.GnomeSort.this' cannot be referenced from a static context
If I remove it, the error goes away, but of course at that point the whole method would be completely useless, since as you can see I'm trying to execute the sort, and return the array.
I honestly don't have anything else to tell you. If you need some further clarification or explenation, please just let me know. I will be back immediately.
Thank you in advance for any help :)
The type
Texists at the bound instance level, you can introduce another generic bound for thestaticmethod. Also, you want to iterate toarrayToSort.length - 1(since you usei + 1to getnextin the loop body). And your swap is backward. Like,Looking at the rest of your code it seems like you don't need
T(or forGnomeSortto be generic at the class level).