MagdalenaTakeva

PO2_Compare_Character_Arrays_Lexicographically

Feb 22nd, 2022
47
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.81 KB | None | 0 0
  1. import java.util.Scanner;
  2.  
  3. public class PO2_Compare_Character_Arrays_Lexicographically {
  4. public static void main(String[] args) {
  5. Scanner scanner = new Scanner(System.in);
  6. char[] arr1 = scanner.nextLine().toCharArray();
  7. char[] arr2 = scanner.nextLine().toCharArray();
  8. boolean arrayEqual = true;
  9.  
  10. // In lexicographic order the elements are compared one by one starting from the very left.
  11. // If the elements are not the same, the array, whose element is smaller (comes earlier in the alphabet),
  12. // comes first.
  13. // If the elements are equal, the next character is compared.
  14. // If the end of one of the arrays is reached, without finding different elements, the shorter array is the smaller
  15. // (comes earlier lexicographically).
  16. // If all elements are equal, the arrays are equal
  17.  
  18. if (arr1.length > arr2.length) {
  19. System.out.println("Second array is lexicographically smaller.");
  20. } else if (arr1.length < arr2.length) {
  21. System.out.println("First array is lexicographically smaller.");
  22. } else {
  23.  
  24. for (int i = 0; i < arr1.length; i++)
  25. {
  26. if (arr1[i] < arr2[i])
  27. {
  28. System.out.println("First array is lexicographically smaller.");
  29. arrayEqual = false;
  30. break;
  31. }
  32. if (arr1[i] > arr2[i])
  33. {
  34. System.out.println("Second array is lexicographically smaller.");
  35. arrayEqual = false;
  36. break;
  37. }
  38. }
  39.  
  40. if (arrayEqual) {
  41. System.out.println("Arrays are lexicographically equal.");
  42. }
  43. }
  44. }
  45.  
  46.  
  47. }
Advertisement
Add Comment
Please, Sign In to add comment