Why Does My Sorting Loop Seem to Append an Element Where It Shouldn'T

Why does my sorting loop seem to append an element where it shouldn't?

Your output is correct. Denote the white characters of " Hello" and " This" at the beginning.

Another issue is with your methodology. Use the Arrays.sort() method:

String[] strings = { " Hello ", " This ", "Is ", "Sorting ", "Example" };
Arrays.sort(strings);

Output:

 Hello
This
Example
Is
Sorting

Here the third element of the array "is" should be "Is", otherwise it will come in last after sorting. Because the sort method internally uses the ASCII value to sort elements.

Can't add objects to an array after a foreach loop in C#

Append will just append to existing elements of array, since in your case size is already defined as 2(new ExerciseAnswer[2]) so it is not appending anything. What you can do is either have a new array and get the elements added to it or just get the index of element you are running the loop and replace same in the array.
Something like below:-
int elementIndex = Array.IndexOf(exerciseAnswers,answer);
exerciseAnswers[elementIndex] = exerciseAnswer;

Why do these list operations (methods: clear / extend / reverse / append / sort / remove) return None, rather than the resulting list?

The general design principle in Python is for functions that mutate an object in-place to return None. I'm not sure it would have been the design choice I'd have chosen, but it's basically to emphasise that a new object is not returned.

Guido van Rossum (our Python BDFL) states the design choice on the Python-Dev mailing list:

I'd like to explain once more why I'm so adamant that sort() shouldn't
return 'self'.

This comes from a coding style (popular in various other languages, I
believe especially Lisp revels in it) where a series of side effects
on a single object can be chained like this:

x.compress().chop(y).sort(z)

which would be the same as

x.compress()
x.chop(y)
x.sort(z)

I find the chaining form a threat to readability; it requires that the
reader must be intimately familiar with each of the methods. The
second form makes it clear that each of these calls acts on the same
object, and so even if you don't know the class and its methods very
well, you can understand that the second and third call are applied to
x (and that all calls are made for their side-effects), and not to
something else.

I'd like to reserve chaining for operations that return new values,
like string processing operations:

y = x.rstrip("\n").split(":").lower()

There are a few standard library modules that encourage chaining of
side-effect calls (pstat comes to mind). There shouldn't be any new
ones; pstat slipped through my filter when it was weak.

How do I sort an array of strings?

Java Strings are Comparables, meaning they have a compareTo method which can be used to compare two such objects. a.compareTo(b) will return a negative value if a is logically less than b, a positive value if a is greater than b or 0 if they are equal.

So you can keep your entire logical flow and just change the comparison check - instead of if (name[y] > name[y+1] ) you'd need to use if (name[y].compareTo(name[y+1]) > 0 ).

Sorting a subset of a list of strings

In this specific case:

array = ['var1', 'var2', 'var3', '2010 a', '2010 b', '2010 c', '2011 a', '2011 b', '2011 c']

array[3:] = sorted(array[3:], key=lambda s:s.split()[::-1])

the various parts of this should be straightforward. Replace the fourth element onwards with the rest of the sorted list, according to a custom key. This custom key will split the element on any whitespace, and then compare them based on the splits in reverse order (last split takes priority).

How to sort certain range of elements only of a String array in java?

Arrays.sort accepts range parameters.

Example sorting array indexes 1 until 3 inclusive:

String[] arr = {"abc", "rst", "pqr", "qwerty", "lmn"};
Arrays.sort(arr, 1, 4);
System.out.println(Arrays.toString(arr));

Sorting String CompareTo

Since you are required to use compareTo, you can implement Collections.sort.

After all values are added in your array, just provide this array to Collections.sort() along with a custom Comparator. But the problem is that the Collections.sort() wouldn't accept an String array, so you also have to convert it to a list using Arrays.asList(yourArray) method.

Suppose this is your array,

String [] args = new String[]{"dddd","cccc","bbbb", "aaaa"};

Now let's use Collections.sort after converting your array to a list and provide it with a Comparator.

Collections.sort(Arrays.asList(args),new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o1.compareTo(o2);
}
});

simple, isn't it ?

If you want to print the sorted values now,

for (String p : args ){
System.out.println(p);
}

Outputs

aaaa
bbbbb
cccc
dddd

Just for your information, if you want to sort in reverse order, replace
return o1.compareTo(o2) with return o2.compareTo(o1)

Inserting String into an array in order

Since you are going to clone the array using for-loop anyways, there is no need to do any kind of sorting here (which should be good news as you said that's not an option). Just insert the new item in its right place when going thorugh the items.

//for loop here to copy items over into the new resized array.
//We use two counters here, ii for the old list and i for the new
int ii = 0, nn = strings.length;
for(int i = 0, n = newSizedList.length; i < n; i++) {

if(ii != nn && (ii != i || strings[ii].compareTo(a) < 0)){
//The item in newSizedList[i] will be taken from the original list if
//we have not already taken all the items from there (ii != nn) and
//a) we have already inserted the new item (ii != i)
//or b) a is alphabetically "greater" than the corresponding item in original array
newSizedList[i] = strings[ii];
ii++;//Keep the other counter in sync
} else {
//Otherwise, this is the place for the new item
newSizedList[i] = a;
}

}


Related Topics



Leave a reply



Submit