I have the below insertion sort function below, previously I was working with strictly an integer array and called the function below as a means of sorting it. Now in the below function, what I want to do is sort this function based on a file of arbitrary data. AM not entirely sure how to approach this. I tried writing the function and including the file path within the function but am guessing that is not entirely correct. Any suggestions on how to approach this correctly?
public static void InsertionSort(int filename[], int size) {
int index, count;
int temp;
index = 1;
Scanner sca = null;
try {
sca = new Scanner(new File(
"C:/Users/Frank/Downloads/wb1913_samp1040.txt"));
while (sca.hasNextLine()) {
while (index < size) {
temp = filename[index];
count = index;
while (count >= 0 && temp <= filename[count - 1]) {
filename[count] = filename[count - 1];
--count;
}
filename[count] = temp;
index++;
}
}
} catch (FileNotFoundException exception) {
} finally {
sca.close();
}
Updated Code:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.Scanner;
public class Driver {
public static void main(String[] args) {
Scanner scanner = null;
String file = "C:/Users/jdavis/Downloads/wb1913_samp1040.txt";
int count;
Word word = new Word();
LinkedList WordList = new LinkedList();
String[] f = {file};
try {
scanner = new Scanner(new File(
"C:/Users/jdavis/Downloads/wb1913_samp1040.txt"));
while (scanner.hasNextLine()) {
String[] Word = scanner.nextLine().split("\t");
word.setWord(Word[0]);
word.setPartsofSpeech(Word[1]);
word.setDefinition(Word[2]);
WordList.InsertAtBack(word);
WordList.Display();
System.out.println("Before sorting: " +Arrays.toString(f));
//sort array
InsertionSort(f);
System.out.println("After sorting: ");
printArray(f);
}
} catch (FileNotFoundException exception) {
} finally {
// scanner.close();
}
count = WordList.CountList();
System.out.println(count);
}
public static void InsertionSort(Comparable[] array) {
Comparable temp;
for(int i = 1; i < array.length; i++)
{
temp = array[i];
int j = 0;
for(j = i; j > 0; j--)
if(temp.compareTo(array[j - 1]) < 0)
array[j] = array[j - 1];
else
break;
array[j] = temp;
}
}
public static void printArray(String[] f){
System.out.println(Arrays.toString(f));
}
}
you can use the below sort method after you get your String
public static String[] dictionaryFormString(String[] s)
{
//
// Sort each individual string element by alphabetical order
//
for (int i = 0; i < s.length; i++)
{
String wordSt = s[i];
if(wordSt == null) continue;
char[] word = wordSt.toCharArray();
Arrays.sort(word);
s[i] = new String(word);
}
return s;
}
I'm assuming here that you are challenging yourself (or someone has challenged you) to write an insertion sort of your own, and that you want to insert each element as you read it from a file.
If you just want to read a file and end up with a sorted array, it would be simpler and more efficient to just slurp it into the array out-of-order, then use Arrays.sort(). Except as a learning exercise, programmers very seldom write sort algorithms nowadays.
You can make your programs much easier to understand by breaking them into more methods - each method does less, and so is easier to understand, but put together they are powerful.
So:
private void readIntoSortedArray(Scanner sca, String[] array) {
while (sca.hasNextLine()) {
insertInto(array, sca.nextLine());
}
}
private void insertInto(String[] array, String line) {
int index = findFirstElementGreaterThan(line);
shiftElementsByOne(array, index);
array[index] = line;
}
... and so on. Here I've given you the "middle" of your chain of methods. You will need to write a method higher in the stack, that prepares a Scanner and calls readIntoSortedArray. And you will need to write the methods called by insertInto(). Maybe those will call yet more methods.
This also means that you can write small programs to drive these sub-methods and check that they work as you expect, in isolation.
String[] testArray = new String[]{"Adam", "Brian", "Dave"};
int index = findFirstElementGreaterThan("Clive");
if(index != 2) {
throw new RuntimeException("Index should be 2 - was " + index);
}
This is a short step away from test-driven development, which is a good thing to adopt early in your studies, because it makes things much easier. (JUnit is a very popular tool that does essentially the same thing, nicer).
If, once you've done this, you feel your program has too many tiny methods, you can always "inline" your sub-methods -- but many feel that the right size for a method is absolutely tiny.
I guess you want an alphabetical sort. You can't compare strings with < and > -- you can use string1.compareTo(string2) (there are other, more flexible ways, but this is OK for now).
public static boolean doesKeyStringOccursEarlyInDict(String string,String key){
int i = Math.min(string.length(), key.length());
int j = 0;
while(j<i){
if(string.charAt(j) > key.charAt(j)){
return true;
}
j++;
}
//else return false as either both were equal or key does not come early in dictionary
return false;
}
public static void insertionSort(String[] s){
for(int i=1;i<s.length;i++){
String key = s[i];
int j = i-1;
while(j>=0 && doesKeyStringOccursEarlyInDict(s[j], key)){
s[j+1] = s[j];
j--;
}
s[j+1]=key;
}
}
public static void main(String[] args) {
//read the file each line
//split it and store it in an arraylist of string as it can grow..repeat it till u have read all the content
ArrayList<String> s = new ArrayList<>();
//get the complete string array
String[] stringarr = (String[]) s.toArray();
//example : String[] stringarr = {"def","xyz","abc","aaa"};
insertionSort(stringarr);
for(String words:stringarr)
System.out.println(words);
}
Above I have given the part that you are looking for.You are already able to read file.So just fill in the blanks in the above code.
Also I was not trying to challenge you rather was encouraging to think first then ask.
After incorporating the above I would encourage you to follow the approach mentioned by Slim and Nishanth.
If you have file that contains string and you want to sort it.
One approach could be to create a string array after reading file (assuming it isn't very big file) and then apply sorting.
// Read from file
String[] words = someFunctionThatReadFileAndReturnArrayOfString(file);
Arrays.sort(words); // or your sorting function
for (String word : words)
{
System.out.println(word);
}
If you want your insertionSort function to be more generic so that it will be independent of data type then you can ask for Comparable object from user as a additional parameter to your function and use it to compare objects in your code.
your method signature would be something like this-
public static void InsertionSort(Object list[],Comparator<Object> compare)
Related
I've recently begun taking a Computer Science course to understand programming more and seem to have hit a roadblock with our lab on ArrayLists. The purpose of the program is to put x amount of strings into an ArrayList and then output the results in descending order.
Ex:Zebra, Deer, Giraffe
Deer
Result:Giraffe, Zebra, Deer
I've looked around online and found a few examples using ArrayList comparators but our professor wants us to do it by filtering out the largest word, printing it, removing it and then continue that loop until all words are printed out.
Here is my code so far:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int length = 0;
String longest = "";
String currentWord = "";
ArrayList <String> DescendArray = new ArrayList<String>();
System.out.println("What would you like to add to the list?");
String userInput = input.next();
while(!userInput.equals("d"))
{
DescendArray.add(userInput);
userInput = input.next();
}
for (int i=0; i < DescendArray.size(); i++)
{
if (DescendArray.get(i).length() > longest.length())
{
currentWord = DescendArray.get(i);
if (currentWord.length() > longest.length())
{
longest = currentWord;
length = longest.length();
}
}
for (int j=1; j < DescendArray.size() -1 ; j++)
{
if (DescendArray.get(j - 1).length() > longest.length())
{
DescendArray.remove(j - 1);
}
System.out.println(longest + " " + length);
}
}
}
}
I'm assuming my error is somewhere in the inner loop but I can't seem to get it to work no matter how many different variations I use.
This is basically what you gotta do:
public class Zoo {
public static void main(String[] args) {
List<String> zoo = new ArrayList<String>();
zoo.add("Zebra");
zoo.add("Deer");
zoo.add("Giraffe");
zoo.add("Deer");
while(!zoo.isEmpty()) {
String bigger = "";
for(String animal : zoo) {
if(animal.length() > bigger.length()) {
bigger = animal;
}
}
System.out.println(bigger);
while(zoo.contains(bigger)) {
zoo.remove(bigger);
}
}
}
}
I'm amazed at the verbosity of other solutions. A much simpler method would be to use a stream:
List<String> original = Arrays.asList("s1", "String 2", "ss3", "s");
List<String> sorted = original.stream()
.sorted((s1, s2) -> s2.length() - s1.length())
.collect(Collectors.toList());
System.out.println(sorted);
Replace "original" with your ArrayList.
Try this, it works for me.
List<String> sorted = list.stream()
.sorted(Comparator.comparingInt(String::length))
.collect(Collectors.toList());
This seems to work. If you don't want to remove repeating animals then remove distinct() method. I omitted creation of the list.
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class Zoo {
public static void main(String[] args) {
List<String> zoo = Arrays.asList("Zebra", "Deer", "Giraffe", "Deer");
String output = zoo.stream()
.distinct()
.sorted((x, y) -> Integer.compare(y.length(), x.length()))
.collect(Collectors.joining(","));
System.out.println(output);
}
}
Under the assumption that duplicate words need not be removed at the same time, such that a duplicate word will be removed in order, and that the list need not be done in alphabetical order (one could sort the list first), and that thread safety is not important, I would avoid using the integer counters and checking the size. Instead, I would run the output loop until everything has been removed.
As an example:
public void doRemove()
{
while (! descendArray.isEmpty()) {
String longest = "";
for (String s : descendArray) {
if (s.length() > longest.length()) {
longest = s;
}
}
if (longest.length() > 0) {
if (descendArray.remove(longest)) {
System.out.println(longest + " (" + longest.length() + ")");
}
}
} // while we stil have things to process
}
When you say descending order are you referring to the length of the string or an alphabetical comparison?
Check out how the QuickSort algorithm can be used for string sorting. You can find information on QuickSort here
The problem seems to be that for each iteration in your for loop, you arrive at Giraffe as your longest word, then you're checking the rest of the list to see if it is longer than Giraffe. Instead of what you have now, I would write something like:
for (int i=0; i < DescendArray.size(); i++)
{
longest = "";
length = longest.length();
int longestIndex = 0;
for (int j=1; j < DescendArray.size() -1 ; j++)
{
currentWord = DescendArray.get(j);
if (currentWord.length() > longest.length())
{
longestIndex = j;
longest = currentWord;
length = longest.length();
}
}
DescendArray.remove(longestIndex);
System.out.println(longest + " " + length);
}
This nested for loop should find the longest word first, store the index and print and remove the entry at that index before it finds the next longest entry.
Here is another variation which can be used, but involves an extra array list:
ArrayList<String> DescendArray = new ArrayList<>();
DescendArray.add("Monkey");
DescendArray.add("Giraffe");
DescendArray.add("Hippo");
DescendArray.add("Zebra");
DescendArray.add("Monkey");
List<String> copy = new ArrayList<>(DescendArray);
for (int i=0; i<DescendArray.size(); i++) {
String longest = "";
for (int j=0; j<copy.size(); j++) {
String current = copy.get(j);
if (current.length() > longest.length()) {
longest = current;
}
}
System.out.println(longest);
while(copy.contains(longest)) {
copy.remove(longest);
}
}
When you need to remove element from the list, iterator is a better way. See below for the code.
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
public class Zoo {
public static void main(String[] args) {
List<String> zoo = new ArrayList<String>();
zoo.add("Zebra");
zoo.add("Deer");
zoo.add("Giraffe");
zoo.add("Deer");
Collections.sort(zoo,new Comparator<String>() {
#Override
public int compare(String o1, String o2) {
return o2.compareTo(o1);
}
});
Iterator<String> iterator=zoo.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
iterator.remove();
}
}
}
To sort an ArrayList based on it's each String length, you can try:
private ArrayList SortwithStrlength(ArrayList templist) {
for(int i=0;i<templist.size();i++)
{
for(int j=0;j<templist.size();j++)
{
String temp;
if(templist.get(i).toString().length()<templist.get(j).toString().length())
{
temp=templist.get(i).toString();
templist.set(i, templist.get(j).toString());
templist.set(j,temp);
}
}
}
return templist;
}
I'm new to programming/coding and have been stuck on a project in school for a few days now. The goal is to take an array full of words (each position is a different word) and sort it alphabetically. I've tried doing some research on stack overflow already, but I'm having a bit of trouble following some of the examples I've found. The class and driver (I'm using a two part setup if you will) both compile fine, no problems there. The problem occurs when I try to use alphaSort from my driver. I receive a null pointer exception for the line marked below. I've had some trouble with these exceptions in the past, so I'm sure it's something small I'm overlooking. As stated however, I'm not yet fluent enough in the java syntax to catch a small error like that.
I figured I should just include the entire method in-case my error is something in the beginning, before the sorting part. What I have so far (i found this on Stack overflow):
public void alphaSort()
{
String alphaList[] = new String[wordList.size()];
int count=0;
//puts wordList into alphaList for easier sorting
while(count<wordList.size()-1)
{
alphaList[count]=wordList.get(count);
count++;
}
int shortestStringIndex;
//sort begins here
for(int j=0; j<alphaList.length -1; j++)
{
shortestStringIndex = j;
for(int i=j+1; i<alphaList.length; i++)
{
if(alphaList[i].trim().compareTo(alphaList[shortestStringIndex].trim())<0) //null pointer exception points here
{
shortestStringIndex = i;
}
}
if(shortestStringIndex !=j)
{
String temp = alphaList[j];
alphaList[j] = alphaList[shortestStringIndex];
alphaList[shortestStringIndex]=temp;
}
}
//prints out results
count=0;
while(count<alphaList.length)
{
System.out.println(alphaList[count]);
alphaOut.print(alphaList[count]);
count++;
}
}
Any help would be greatly appreciated. Please be as thorough as possible in giving an answer (as i said, I'm a bit of a java newbie). Thanks :)
edit: to test for null values (which i assume are spots in my array list that are blank) i made the following method:
public void isNull()
{
int count=0;
while(count<wordList.size()-1)
{
if((wordList.get(count)).equals(""))
{
System.out.println("null");
break;
}
else
{
System.out.println("nothing yet");
}
count++;
}
}
the while loop never broke early, my method ran to completion.
You need to update the first while loop to match:
while(count < wordList.size()) {
alphaList[count] = wordList.get(count);
count++;
}
You aren't copying over every index of the list to the array, which means that when it goes to check the last index, it cannot find a value (NullPointerException).
Edit:
Here's my full test class that works:
import java.util.ArrayList;
public class Test {
public static void main(String[] args) {
new Test();
}
private ArrayList<String> wordList = new ArrayList<String>();
public Test() {
wordList.add("Test");
wordList.add("Bee");
wordList.add("Pig");
wordList.add("Dog");
alphaSort();
}
public void alphaSort() {
String[] alphaList = new String[wordList.size()];
int count = 0;
while(count < wordList.size()) {
alphaList[count] = wordList.get(count);
count++;
}
int shortestStringIndex;
for(int j = 0; j < alphaList.length - 1; j++) {
shortestStringIndex = j;
for(int i = j + 1; i < alphaList.length; i++) {
if(alphaList[i].trim().compareTo(alphaList[shortestStringIndex].trim()) < 0) {
shortestStringIndex = i;
}
}
if(shortestStringIndex != j) {
String temp = alphaList[j];
alphaList[j] = alphaList[shortestStringIndex];
alphaList[shortestStringIndex]= temp;
}
}
count = 0;
while(count < alphaList.length) {
System.out.println(alphaList[count++]);
}
}
}
Output:
Bee
Dog
Pig
Test
Try this...
// sorting array
if(wordList.size()>0){
String alphaList[] = new String[wordList.size()];
//convert list to String array
alphaList= wordList.toArray(alphaList);
//sorting
Arrays.sort(alphaList);
}
........
// let us print all the elements available in wordList
if(wordList.size()>0){
for (String word: alphaList) {
System.out.println("word= " + word);
}
}
There is an error when you are copying your List to an array. It is inserting a null at the end of the list which is causing your NullPointerException. Here is the revised version that works. Instead of looping through the List and copying each item to the array(which is buggy) I just use the standard java method that is on a List to convert the List to an array.
public static void alphaSort()
{
String alphaList[] = wordList.toArray(new String[]{});
int shortestStringIndex;
//sort begins here
for(int j=0; j<alphaList.length -1; j++)
{
shortestStringIndex = j;
for(int i=j+1; i<alphaList.length; i++)
{
if(alphaList[i].trim().compareTo(alphaList[shortestStringIndex].trim())<0) //null pointer exception points here
{
shortestStringIndex = i;
}
}
if(shortestStringIndex !=j)
{
String temp = alphaList[j];
alphaList[j] = alphaList[shortestStringIndex];
alphaList[shortestStringIndex]=temp;
}
}
//prints out results
int count=0;
while(count<alphaList.length)
{
System.out.println(alphaList[count]);
alphaOut.print(alphaList[count]);
count++;
}
}
The problem is that you're adding wordList.size()-1 number of items into the array and the array size is wordList.size() which means that the last value in the array is null
For this while loop:
while (count<wordList.size()-1)
{
alphaList[count]=wordList.get(count);
count++;
}
you don't need to loop to wordList.size()-1 since you already do < instead of <=. You are stopping your loop at the second to last index and are thus not assigning a value to the last place in the array. Instead do while (count < wordList.size()) or while (count <= wordList.size()-1)
I am trying to remove duplicated words from an array, and I keep getting null values. I'm not allowed to use java sorting methods so I have to develop my own. Here's my code:
public class Duplicate{
public static void main(String[] args){
String[] test = {"a", "b", "abvc", "abccc", "a", "bbc", "ccc", "abc", "bbc"};
removeDuplicate(test);
}
public static String[] removeDuplicate(String[] words){
boolean [] isDuplicate = new boolean[words.length];
int i,j;
String[] tmp = new String[words.length];
for (i = 0; i < words.length ; i++){
if (isDuplicate[i])
continue;
for(j = 0; j < words.length ; j++){
if (words[i].equals(words[j])) {
isDuplicate[j] = true;
tmp[i] = words[i];
}
}
}
for(i=0;i<words.length;i++)
System.out.println(tmp[i]);
return tmp;
}
}
I tried doing
if(words == null)
words == "";
But it doesn't work. I also want to return the tmp array with a new size.
For example, test array length = 9, after removing the duplicates,I should get a new array with a length of 7.Thank you for your help.
EDIT:
result i get:
a
b
abvc
abccc
null
bbc
ccc
abc
null
You're getting nulls because the result array contains fewer words than the input array. However, you're constructing the arrays of the same length.
You don't have to sort to solve this problem. However, if you're not allowed to use the tools provided by java.utils, then this is either a poorly contrived test question or whomever told you not to use the Java utility classes is poorly informed.
You can solve without sorting by doing (assuming Java 1.5+):
public class Duplicate {
public static void main(String[] args) {
String[] test = {"a", "b", "abvc", "abccc", "a", "bbc", "ccc", "abc", "bbc"};
String[] deduped = removeDuplicate(test);
print(deduped);
}
public static String[] removeDuplicate(String[] words) {
Set<String> wordSet = new LinkedHashSet<String>();
for (String word : words) {
wordSet.add(word);
}
return wordSet.toArray(new String[wordSet.size()]);
}
public static void print(String[] words) {
for (String word : words) {
System.out.println(word);
}
}
}
The output will be:
a
b
abvc
abccc
bbc
ccc
abc
I would go for hashset to remove duplicates, it will remove duplicates since hash function for the same string will give same value, and duplicates will be eliminated. Then you can convert it to a string.
I would recommend doing this with a different approach. If you can use an ArrayList, why not just create one of those, and add the non-duplicate values to it, like this:
ArrayList<String> uniqueArrayList = new ArrayList<String>();
for(int i = 0; i < words.length; i++){
if(!uniqueArrayList.contains(words[i])){ // If the value isn't in the list already
uniqueArrayList.add(words[i]);
}
}
Now, you have an array list of all of your values without the duplicates. If you need to, you can work on converting that back to a regular array.
EDIT
I really think you should use the above option if you can, as there is no clean or decently efficient way to do this only using arrays. However, if you must, you can do something like this:
You can use the code you have to mark values as null if they are duplicates, and also create a counter to see how many unique values you have, like this:
int uniqueCounter = 0;
for(int i = 0; i < isDuplicate.length; i++){
if(!isDuplicate[i]){
uniqueCounter++;
}
}
Then, you can create a new array of the size of unique items, and loop through the words and add non-duplicate values.
String[] uniqueArray = new String[uniqueCounter];
int uniqueIndex = 0;
int wordsIndex = 0;
while(index < uniqueArray.length){
// Check if words index is not a duplicate
if(!isDuplicate[wordsIndex]){
// Add to array
uniqueArray[uniqueIndex] = words[wordsIndex];
uniqueIndex++; // Need to move to next spot in unique.
}
// Need to move to next spot in words
wordsIndex++;
}
Again, I HIGHLY recommend against something like this. It is very poor, and pains me to write, but for the sake of example on how it could be done using an array, you can try it.
I don't have the time to write functioning code, but I would reccomend to first sort the array using Arrays.sort(stringArray) and then loop throug the array coparing one string to the previous. Strings that match the previous one are duplicates.
Note: This method is probably not the fastest one and though only should be used on small arrays or in tasks where performance does not matter.
What about this approach?
public static String[] removeDuplicate(String[] words){
// remember which word is a duplicate
boolean[] isDuplicate = new boolean[words.length];
// and count them
int countDuplicate = 0;
for (int i = 0; i < words.length ; i++){
// only check "forward" because "backwards checked" duplicates have been marked yet
for(int j = i + 1; j < words.length ; j++){
if (words[i].equals(words[j])) {
isDuplicate[j] = true;
countDuplicate++;
}
}
}
// collect non-duplicate strings
String[] tmp = new String[words.length - countDuplicate];
int j = 0;
for (int i = 0; i < isDuplicate.length; i++) {
if (isDuplicate[i] == false) {
tmp[j] = words[i];
j++;
}
}
// and return them
return tmp;
}
I want to sort a input.txt file and save it in output.txt for instance. I use the insertion sort algorithm. Now my problem: the compareTo method seems to work incorrectly (or at least not how I want to to work). It returns integer greater than 1 thus the algorithm does not really especially for negative numbers. I hope you guys can help me with that problem, thanks!
Thats my code:
import java.util.ArrayList;
import java.io.*;
class Isort
{
public static void main(String[] args)
{
if(args[0].equals("int"))
{
ArrayList<Integer> array = new ArrayList<Integer>();
sort(array, args[1], args[2]);
}
else if(args[0].equals("float"))
{
ArrayList<Float> array = new ArrayList<Float>();
sort(array, args[1], args[2]);
}
else if(args[0].equals("String"))
{
ArrayList<String> array = new ArrayList<String>();
sort(array, args[1], args[2]);
}
else
{
//do nothing
}
}
public static <T extends Comparable<T>> void sort(ArrayList<T> array, String input, String output)
{
try
{
File file = new File(input);
BufferedReader reader = new BufferedReader(new FileReader(file));
reader.mark((int)file.length() + 1);
int count = 0;
while(reader.readLine() != null)
{
count++;
}
reader.reset();
for(int i = 0; i<count; i++)
{
array.add((T)(reader.readLine()));
}
reader.close();
int j;
T temp;
for(int i = 1; i < array.size(); i++)
{
j = i;
while(j > 0 && array.get(j-1).compareTo(array.get(j)) > 0)
{
temp = array.get(j);
array.set(j,array.get(j-1));
array.set(j-1,temp);
j -= 1;
System.out.println(array);
}
}
PrintWriter writer = new PrintWriter(output);
for(int i = 0; i<array.size(); i++)
{
writer.write(String.valueOf(array.get(i)));
writer.write(System.getProperty ("line.separator"));
}
writer.flush();
writer.close();
}
catch(FileNotFoundException e)
{
}
catch(IOException e)
{
e.printStackTrace();
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
}
I believe you are confused by the use of generics. You are making generic ArrayLists of Integer, Long and String. You are then reading a line of text and attempting to cast it to T.
This will not do anything at runtime due to type-erasure. In all of the cases above (int, long and string) you will be passing an ArrayList<Object> and adding String to the list. When you read the String from the file the cast doesn't do anything except cast it to an Object which String already is. So unless the compareTo of String matches your requirements for int and long this will not work.
In reply to comment...
That's the point. Casting to T or really using generics at all in this case don't do what you need. In all cases you are reading and comparing String. Instead you need to have three methods readInt, readLong and readString and call the appropriate one based on what you are expecting. One option would be to use an interface of readNextValue and pass in an appropriate implementation depending on the situation.
I suggest you to using a "Comparator" class in "Collections.sort(...)" method. You can find an example here-> http://www.vogella.com/blog/2009/08/04/collections-sort-java/.
I tried sorting strings using bubblesort, but I dont know whether it makes any sense but can someone just help me figure out how to sort strings and let me know if my logic is correct? i have converted the strings to character just to check if they are in alphabetical order..eg app ban acc will be sorted to acc app and ban..can anyone give the logic to this problem.
import java.io.*;
import java.util.*;
class sort
{
public static void main(String args[])throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter the strings");
String str=br.readLine();
StringTokenizer st=new StringTokenizer(str,",");
String s1=st.nextToken();
String s2=st.nextToken();
String s3=st.nextToken();
char ch1[]=s1.toCharArray();
char ch2[]=s2.toCharArray();
char ch3[]=s3.toCharArray();
if ((ch1[0]<ch2[0])&&(ch1[0]<ch3[0])&&(ch2[0]<ch3[0]))
for(int i=0;i<4;i++)
{
System.out.println(+ch1[i]);
System.out.println(+ch2[i]);
System.out.println(+ch3[i]);
}
else if((ch2[0]<ch1[0]&&ch2[0]<ch3[0]&&ch1[0]<ch3[0]) )
for(int i=0;i<4;i++)
{
System.out.println(+ch2[i]);
System.out.println(+ch1[i]);
System.out.println(+ch3[i]);
}
else if((ch3[0]<ch1[0])&&(ch3[0]<ch2[0])&&ch1[0]<ch2[0])
for(int i=0;i<4;i++)
{
System.out.println(+ch3[i]);
System.out.println(+ch1[i]);
System.out.println(+ch2[i]);
}
}
}
Bubble sort, also known as sinking sort, is a simple sorting algorithm that works by repeatedly stepping through the list to be sorted, comparing each pair of adjacent items and swapping them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, which indicates that the list is sorted. The algorithm gets its name from the way smaller elements "bubble" to the top of the list. Because it only uses comparisons to operate on elements, it is a comparison sort. Although the algorithm is simple, it is not efficient for sorting large lists; other algorithms are better. Wikipedia
The following is the sort-cut way to do so.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
final public class Main
{
public static void main(String[] args) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter the strings:->");
String str=br.readLine();
String strArr[]=str.split(" ");//your sentence will be split into words.
Arrays.sort(strArr);
for(int i=0;i<strArr.length;i++)
{
System.out.println(strArr[i]);
}
}
}
If you wish, you can apply your own logic as follows.
final public class Main
{
public static void main(String[] args) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter the strings:->");
String str=br.readLine();
String strArr[]=str.split(" ");
String temp;
for(int i = 0; i<strArr.length - 1; i++)
{
for(int j = 0; j<strArr.length - 1; j++)
{
if(strArr[j].compareTo(strArr[j+1]) > 0)
{
temp = strArr[j];
strArr[j] = strArr[j+1];
strArr[j+1] = temp;
}
}
}
for(int i=0;i<strArr.length;i++)
{
System.out.println(strArr[i]);
}
}
}
In both the cases, I have assumed spaces as word separator and not commas , that you're using in your example.
First you need to choose how do you want to sort strings ?
is it by length ? is it by alpha order ?
After you choose the appropriated method, you just need to sync it for the existing sorting method of bubblesort.
public static int[] bubble(String[] str_arr) {
for (int i = 0, temp; i < str_arr.length-1; i++) {
for(int j = 0; j < str_arr.length-1; j++) {
if (str_arr[j] < str_arr[j+1]) {
temp = str_arr[j];
str_arr[j] = str_arr[j+1];
str_arr[j+1] = temp;
}
}
}
return str_arr;
}
As i mentions theres couple of ways of comparing strings:
Length - length of a string
Lexicographically - explanation here
If we want to use one of the two method mentioned above, we should change the line:
if (str_arr[j] < str_arr[j+1])
to
if (str_arr[j].length < str_arr[j+1].length)
Or for the lexicographically order we will use:
if (str_arr[j].compareTo(str_arr[j+1].length) < 0)
compareTo is a java String method that checking lexicog.. order.
it returnes:
0 - strings are identical.
positive number - first string is bigger then second string.
negative number - first string is smaller then second string.
String implements interface Comparable (so overrides compareTo() method), thus you can compare two strings (>,<,>=,<=). That's why you don't have to compare every char element by element. Not worth trying even.
The solution: put Strings into array:
String[] stringArray = new String[]{"element1","element2"};
and then use default bubble-sort algorithm:
for (int x = 1; x < stringArray.length; x++) {
for (int y = 0; y < stringArray.length - x; y++) {
if (stringArray[y].compareTo(stringArray[y + 1]) > 0) {
temp = stringArray[y];
stringArray[y] = stringArray[y + 1];
stringArray[y + 1] = temp;
}
}
}
and you should receive sorted array.