Can you explain what is happening after Arrays.sort(arr); ? [Solved] | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Can you explain what is happening after Arrays.sort(arr); ? [Solved]

public class Countduplicate { // if a given string is isogram or not static boolean is_isogram(String str) { // Convert the string in lower case letters str = str.toLowerCase(); int len = str.length(); char arr[] = str.toCharArray(); Arrays.sort(arr); for (int i = 0; i < len - 1; i++) { //why we use -1 here? if (arr[i] == arr[i + 1]) //and +1 here? return false; } return true; } } https://code.sololearn.com/c5a22a0a11a1/?ref=app

6th Mar 2021, 2:41 PM
Ray
Ray - avatar
4 Answers
+ 2
The toCharArray() method converts a string into a char[] array of its constituent characters. Suppose a string - "CAB". The ASCII value of C, A and B are 67, 65, and 66 respectively. These values are mapped into an array. So if we do "CAB".toCharArray(), the array will look like this - [67, 65, 66] (While comparing, it'll automiactlly get converted into ints). Since these are numbers, the Arrays.sort() method arranges the array into ascending order of the numbers. So the resultant array will be this - [65, 66, 67]. The for loop is used to check if the string consists of a character more than once i.e. if it's an isogram string. Let me explain how that works. Suppose a String "soumik". After converting this to an array of chars, it'll look something like - [115, 111, 117, 109, 105, 107]. Now in the for loop, we need to check if two consecutive numbers are equal (since these are ints). Remember that we had sorted our array. So the final array will contain numbers in ascending order. (continued below)
6th Mar 2021, 2:52 PM
Soumik
Soumik - avatar
+ 3
[contd.] So the final array will be [105, 107, 109, 111, 115, 117]. We need to compare two elements of the array. Arrays are indexed with zero so 1st element's index is 0. for(int i = 0; i < len - 1; i++) is the loop. At every iteration, we check ar[i] and ar[i + 1] because when you reach the last iteration of the loop, you have the number whose value is length of the array - 2 (since it's < sign). Let's take our array [105, 107, 109, 111, 115, 117]. This has 6 elements. So len = 6. At last iteration of the loop, i = 4 and i + 1 = 5. This is why you go upto len - 1. Check this code and the comments in it. Maybe it'll help you! https://code.sololearn.com/ct72f6tEsne6/?ref=app
6th Mar 2021, 3:07 PM
Soumik
Soumik - avatar
+ 2
Thanks ♨ Soumik 🎶 for taking your valuable time to explain me this 🙏😭
6th Mar 2021, 4:24 PM
Ray
Ray - avatar
+ 1
Rabeeh You're welcome :)
6th Mar 2021, 4:54 PM
Soumik
Soumik - avatar