JAVA: LinkedList
Example: this is just a test should become: a is this just test
I am trying to order them with the comparable interface and saying that if the length of string at position i is the same as string at position i+1 (this is in a for loop) it should return 0, and then the bigger/smaller cases. but when i then use collections.sort(mylinkedlist) it still orders it lexicographically. Am I doing something wrong?
to be clear, you mean the Comparator interface not Comparable -- that String class is already Comparable and there is no changing that logic. Looking above, your expected "sort" ordering makes no sense. based on what I see, you essentially want them is ascending order by length. Your explanation though doesn't make that case but your example does. if you want to sort by lexigraphical and make length a tie breaker then then make that an optional step in a Comparator if the Strings lexically sort the same. Ultimately though, I think you really misunderstand the nature of sorting. Sorting algorithms don't work by comparing "a[i], a[i+1]" -- generally speaking they look at just 2 elementals and decide which is "less". Indexing an array is for performance and managing in-memory sorts. When the comparison occurs you just have 2 elements and not their position in any data structure. Remember to, Comparator/Comparable isn't just used for sorting Lists/Arrays -- TreeMap uses it as well and there is NO such thing as an index there. Comparator doesn't supply indicies with the call because they are not part of the nature of sorting. Bottom line: 1) Make clearer what you want or 2) Sort by length or 3) Sort by lexi and if there is a tie, then by length 4) Read http://en.wikipedia.org/wiki/Bubble_sort (Collection.sort uses quick sort btw)
Let me amend my last post: Lexigraphical sorting is by < -- bucket sorting is not (That's right, sorting isn't just through comparison)
I figured it out - it's using stable sort
Join our real-time social learning platform and learn together with your friends!