Sorting Flashcards
Give the signature of Arrays.sort method !
You can pass almost any array to Arrays.sort :
(here is a few ones)
public static void sort(int[] a)
public static void sort(double[] a)
public static void sort(float[] a)
public static void sort(char[] a)
Describe the behavior of Arrays.sort method when sorting an array of strings that contain letters and numbers !
EXAMPLE 1 :
int[] numbers=new int[]{3,2,1};
System.out.println(Arrays.toString(numbers));
// [3,2,1]
Arrays.sort(numbers); System.out.println(Arrays.toString(numbers));
// [1,2,3]
EXAMPLE 2 :
String[] numbers=new String[]{“Morocco”,”Brazil”,”France”};
System.out.println(Arrays.toString(numbers)); // [Morocco, Brazil, France]
Arrays.sort(numbers);
System.out.println(Arrays.toString(numbers)); // [Brazil, France, Morocco]
EXAMPLE 3 :
String[] numbers=new String[]{“mOrocco”,”bRazil”,”fRance”};
System.out.println(Arrays.toString(numbers)); // [mOrocco, bRazil, fRance]
Arrays.sort(numbers);
System.out.println(Arrays.toString(numbers)); // [bRazil, fRance, mOrocco]
EXAMPLE 4 :
String[] numbers=new String[]{“morocco”,”brazil”,”France”};
System.out.println(Arrays.toString(numbers)); // [morocco, brazil, France]
Arrays.sort(numbers);
System.out.println(Arrays.toString(numbers)); // [France, brazil, morocco]
IMPORTANT :
Java compares the characters of numerical strings one by one from left to right. It starts by comparing the first characters of each string and proceeds to subsequent characters until a difference is found or one of the strings ends.
If all characters match until the end of one of the strings, the shorter string is considered lesser than the longer one. If the lengths are equal and all characters match, the strings are considered equal.
The problem is that String sorts in alphabetic order, and 1 sorts before 9
(Numbers sort before letters and uppercase sorts before lowercase, in case you were wondering.)
What is the relationship between chars and numbers ?
In Java, characters (char) and numbers (int, byte, short, long, etc.) are closely related due to the underlying representation of characters as integer values in the Unicode character set
Unicode Representation: Characters in Java are represented using the Unicode encoding system, where each character is associated with a unique integer value. For example, the character ‘A’ has a Unicode code point of 65.
Char to Int: You can implicitly convert a char to an int, which will yield the Unicode code point of the character
You can also convert an int to a char, as long as the integer value falls within the valid range of Unicode code points (0 to 65,535)
Since characters are essentially represented as integers, you can perform arithmetic operations on char values.
For EXAMPLE :
char a = ‘A’;
char b = (char) (a + 1); // b will be ‘B’