1// how to sort string array in java without using sort method
2import java.util.Arrays;
3public class SortStringArray
4{
5 public static void main(String[] args)
6 {
7 String[] strPlaces = {"Great Barrier Reef", "Paris", "BoraBora", "Florence","Tokyo", "Cusco"};
8 int size = strPlaces.length;
9 for(int a = 0; a < size - 1; a++)
10 {
11 for(int b = a + 1; b < strPlaces.length; b++)
12 {
13 if(strPlaces[a].compareTo(strPlaces[b]) > 0)
14 {
15 String temp = strPlaces[a];
16 strPlaces[a] = strPlaces[b];
17 strPlaces[b] = temp;
18 }
19 }
20 }
21 System.out.println(Arrays.toString(strPlaces));
22 }
23}
1// java program to sort an array using Arrays.sort() method
2import java.util.Arrays;
3public class JavaArraySortMethod
4{
5 public static void main(String[] args)
6 {
7 String[] strGiven = {"Great Barrier Reef", "Paris", "borabora", "Florence","tokyo", "Cusco"};
8 Arrays.sort(strGiven);
9 System.out.println("Output(case sensitive) : " + Arrays.toString(strGiven));
10 }
11}
1import java.util.Arrays;
2
3public class Test
4{
5 public static void main(String[] args)
6 {
7 String original = "edcba";
8 char[] chars = original.toCharArray();
9 Arrays.sort(chars);
10 String sorted = new String(chars);
11 System.out.println(sorted);
12 }
13}
14
1String[] myArray = {"JavaFX", "HBase", "OpenCV", "Java", "Hadoop","Neo4j"};
2Arrays.sort(myArray);
3System.out.println(Arrays.toString(myArray));
1public class ArrayReturn3 {
2
3 public static String[] sortNames(String[] userNames) {
4 String temp;
5 for (int i = 0; i < userNames.length; i++) {
6 for (int j = i + 1; j < userNames.length; j++) {
7 if (userNames[i].compareTo(userNames[j]) > 0) {
8 temp = userNames[i];
9 userNames[i] = userNames[j];
10 userNames[j] = temp;
11 }
12 }
13 }
14 return userNames;
15 }
16
17 public static void main(String[] args) {
18 String[] names = {"Ram", "Mohan", "Sohan", "Rita", "Anita", "Nita", "Shyam", "Mukund"};
19 System.out.println("Names before sort");
20 for (String n : names) {
21 System.out.print(" " + n);
22 }
23 String[] sortedNames = sortNames(names);
24 System.out.println("\nNames after sort (Sent name)");
25 for (String n : names) {
26 System.out.print(" " + n);
27 }
28 System.out.println("\nNames after sort (Received name)");
29 for (String n : sortedNames) {
30 System.out.print(" " + n);
31 }
32 }
33}