2

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]);
            }
    }
}
9
  • 4
    One ugly looking code. What are you trying to sort? Commented Dec 31, 2011 at 13:41
  • Is this a homework task? Commented Dec 31, 2011 at 13:43
  • 2
    MakesNoSenseLogicalException. Commented Dec 31, 2011 at 13:43
  • What's that? Are you really following a right method to sort strings in your program? I don't think so? Commented Dec 31, 2011 at 13:44
  • 2
    Then use java.util.Arrays.sort(). Boom, one line, you're done. Commented Dec 31, 2011 at 13:54

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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:

  1. Length - length of a string
  2. 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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.