This is a sample Java program to demonstrate string sorting.
The function uses a space character as a separator between words. It iterates through each word in the input string and creates a words[] array.
Finally it sorts the array of the words in ascending order of the letters i.e. a->z and displays the sorted array by printing one word at each line.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 | public class Sort { public static void main(String[] args) { // Declare the String that is to be sorted. String text = "This website is developed to help anyone who wants to learn C/C++ programming There are plenty of resources for learners such as tutorials source code library references programming syntax and programming interview questions"; int index = 0; char separator = ' '; // inter-word separating character int count = 1; // Count number of words. There must be at least 1 // This is the reason for a do-while rather than // a while loop in the example Word for Word. // Determine how many words there are while ((index = text.indexOf(' ', index)) != -1) { index++; count++; } // Create the array of strings to contain all the words. String[] words = new String[count]; index = 0; int endIndex = 0; for (int i = 0; i < count; i++) { endIndex = text.indexOf(separator, index); // find the next separator if (endIndex == -1) words[i] = text.substring(index); else words[i] = text.substring(index, endIndex); index = endIndex + 1; } // Sort the substring array using direct insertion { int i, j; String a; for (j = 1; j < count; j++) // Look at every word starting at 2nd { a = words[j]; // Put the current word in a buffer i = j - 1; // Start compare with the previous word while ((i >= 0) && (words[i].compareTo(a) > 0)) { // Compare the ith and i+1th word - if ith word words[i + 1] = words[i]; // is greater than i+1th, swap them i--; // Decrease i so the previous pair are compared } // next time round words[i + 1] = a; // If any changes to the array occur, the } // word at j is gone. Put the stored word in } // the vacant place. // Display the sorted array of words for (int i = 0; i < words.length; i++) System.out.println(words[i]); } } |
The output of the Java program is as below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | C/C++ There This and anyone are as code developed for help interview is learn learners library of plenty programming programming programming questions references resources source such syntax to to tutorials wants website who |
See also: Shell Sort, Quick Sort, Bubble Sort, Insertion Sort, Selection Sort