Sorting 2Darrays in java

  • Thread starter Thread starter peeweegary
  • 8 comments
  • 726 views

peeweegary

(Banned)
Messages
1,030
Messages
GTP_peeweegary, peeweegary
Hey all.
Is it possible to sort letters a-z, A-Z that have been stored in a String array or do the letters have to be converted to ascii first?

The array has a total of 54 spaces each filled with a letter.

This is all for a school assignment but the general coding for this was never in the class notes.

Thanks in advance:)
 
You should be able to run a straight compareTo(), as a < z < A < Z in Java anyway. No need to convert to ASCII.

If you'd like I can post up how I was taught to do it [for loop + compareTo(charAt(x))].
 
oooo yes please...Im only taking grade 11 computer science so i dont know much of java yet. Barely scratching the surface of java.
 
Oops, sorry for forgetting about this thread :dunce:

Using bubble sort (really bad idea, I know... lol)
PHP:
public void sort(String[] array){
   int pass = 1;
   boolean swaps = false;
  do {
     swaps = false; //nothing has been swapped yet
     //compare each adjacent element
    for(int i = 0; i < array.length - pass; i++) {
        if(array[i].compareTo(array[i+1]) > 0) {
          //swap pair of characters
          String temp = array[i];
          array[i] = array[i+1];
          array[i+1] = temp;
          swaps = true;
         } //closing if
     } //closing for
     pass++;
  } while (swaps); //closing do, string array is now sorted
} //closing method

Of course, you can cheat by calling Arrays.sort(stringArray) if you import java.util.Arrays! :lol:
 
thanks sharky =)

EDIT: How would this work if the array was 2D?
 
Last edited:
You mean 3D? Is it even possible to sort a 3D array? :lol:

edit: ah, I'm confusing myself. :dunce: I'd imagine you could run the sort on both directions of the array - bubble the "largest" character in each "row" of the array to the end and bubble the largest in each "column" down to the bottom. When I first read the thread I though you were referring to normal arrays. :dunce:
 
Last edited:
How would you sort a 2-dimensional array? You could sort each sub array, but would prioritise one array over another?
 
I had an idea where you convert the 2D array to a 1D array: basically stitch each row to the end of the previous, then sort the resultant 1D array, then "redimensionify" - put back into a 2D array.

Voila! Sorted, and 2D.
 
^^thats what i said to my friend but apparently in the rubric, to obtained a level 4 we have to sort the input in a 2D array....

What you said would've just gotten me a level 3 -_-'...I hate this :(

Oh well i'll what what you said Sharky...its better than having nothing.

Thanks fellas 👍
 
Back