Welcome to Dream.In.Code
Become a Java Expert!

Join 149,617 Java Programmers for FREE! Get instant access to thousands of Java experts, tutorials, code snippets, and more! There are 1,861 people online right now. Registration is fast and FREE... Join Now!




user-defined method with string and selection sort

 
Reply to this topicStart new topic

user-defined method with string and selection sort, output numbers in the string in ascending order using selection sort (

jei_monsterkid
21 Aug, 2007 - 12:29 AM
Post #1

New D.I.C Head
*

Joined: 5 Jul, 2007
Posts: 1


My Contributions
i will have to use user defined method. my program should accept a string of numbers and characters. output all the numbers found in the string and display these numbers in ascending order. use method to do the selection sort.

here's my main:
CODE

/*Extrapoint*/

import java.io.*;
import java.util.*;


public class String{

    static Scanner con=new Scanner (System.in);
    public static void main( String [] args){

        String str;
        int length;
    System.out.println("Input a string of letters and numbers:");
    str= con.next();
        length = str.length();
        process(str,length);
    }
    public static void process (String str1, int length1)
    {
    int i = 0;
    System.out.println("The numbers in the string are: ");
    for (i=0; i<length1; i++)
    {
    if(Character.isDigit(str1.charAt(i)))
        System.out.print(str1.charAt(i)+ " ");

    }

    System.out.println();

    }
}



(i am not sure with my variables)
and the user defined is:

CODE

public static void BubbleSort(int [] list,int listLength)
          {
                     int x;
                       int c, index;

                      for (c=0; c<listLength-1; c++)
          {
                      for (index=0; index<listLength-1; index++)
          {

                      if (list[index]>list[index+1])
          {
                          x=list[index];
                          list[index] = list[index+1];
                          list[index+1] = x;
          }
          }
          }

          }


}


thanx..
User is offlineProfile CardPM
+Quote Post

Martyr2
RE: User-defined Method With String And Selection Sort
21 Aug, 2007 - 10:53 AM
Post #2

Programming Theoretician
Group Icon

Joined: 18 Apr, 2007
Posts: 5,655



Thanked: 313 times
Expert In: C/C++, Java, VB, VB.NET, C#, PHP, Web Development, HTML & CSS, Javascript

My Contributions
The solution I have designed for you have a bit of "kookyness" in it so I will have to explain what I am doing and why. I created this solution using an actual selection sort algorithm because I wasn't sure if you wanted the selection sort you mention in the topic or the bubble sort you provided. So I wrote it with the idea that you could drop in a bubblesort if you needed by replacing the function and making sure it takes an array and returns a sorted array.

Now I am not a big fan of changing a person's program all around more than need be to get a solution. In sticking with this mentality, I tried to build on what you had implemented already like using charAt() and primitive datatype arrays etc. One place where this gets sticky is when converting a charAt over to the integer value needed for sorting appropriately. I pass the char to the valueOf to get it to a string that I could then use in a parseInt to make sure it was an integer. The solution works out nicely, but it looks funny doing it.

So here is the solution...

CODE

import java.io.*;
import java.util.*;


public class String1 {

    public static Scanner con = new Scanner(System.in);

    // Main program start point.
    public static void main(String [] args) {
        int length;

        System.out.println("Input a string of letters and numbers:");
        String str = con.next();

        length = str.length();

        process(str,length);
    }


    // Process the entered input and determine if it is a number.
    public static void process (String str1, int length1)
    {
        int i = 0, numbercount = 0;
        int[] numbers = new int[length1];

        // Initialize entire array with invalid value
        for(int f = 0; f < numbers.length; f++) {
                numbers[f] = -1;
        }

        for (i=0; i<length1; i++)
        {
                // If number, convert it to an integer to store
                if(Character.isDigit(str1.charAt(i))) {
                        numbers[numbercount] = Integer.parseInt(String.valueOf(str1.charAt(i)));
                        numbercount++;
                }        
        }

        // Sort the array and store it in new sorted array
        int[] sortednumbers;
        sortednumbers = selectionSort(numbers);

        // Now print it
        printArray(sortednumbers);
        System.out.println();

    }


    // This is a custom selection sort, but you could easily make it bubble
    // by making sure it takes an integer array and returns a sorted array.

    private static int[] selectionSort(int[] numArray) {
        for (int i = 0; i < numArray.length - 1; i++) {
            for (int j = i + 1; j < numArray.length; j++) {
                    if (numArray[i] > numArray[j]) {
                        int swap = numArray[i];
                        numArray[i] = numArray[j];
                        numArray[j] = swap;
                    }
            }
        }
        return numArray;
    }


    // This function loops through our sorted numbers and prints
    // only those elements which are numbers

    private static void printArray(int[] printArray) {
        String result = "";
        for (int i = 0; i < printArray.length; i++) {
                if (printArray[i] > -1) {
                        if (result.equals("")) {
                                result += printArray[i];
                        }
                        else { result += ", " + printArray[i]; }
                }
        }

        System.out.println("Sorted Numbers: " + result);

    }    
}


One thing I want to point out is the use of the -1 value in the array to mark invalid array entries. I look for this in the print to know if I have actually have a legit value in the array since the selection sort will push all legit values to the end of the array. I could reverse the sort order in the algorithm, but not knowing if you are going to change it later I didn't bother.

To make a more elegant solution I would have considered using an ArrayList or implement a Linked List so that I didn't have to loop through the entire array looking for valid entries. I again wasn't sure how far along you were and if you had experience in those solutions. So I opted for the more basic way.

Hope you find this solution ok since it does what you want, modify it whatever way you like.

decap.gif

This post has been edited by Martyr2: 21 Aug, 2007 - 10:54 AM
User is offlineProfile CardPM
+Quote Post

goingse
RE: User-defined Method With String And Selection Sort
21 Aug, 2007 - 11:22 AM
Post #3

New D.I.C Head
*

Joined: 26 Jul, 2007
Posts: 3


My Contributions
QUOTE(Martyr2 @ 21 Aug, 2007 - 11:53 AM) *

The solution I have designed for you have a bit of "kookyness" in it so I will have to explain what I am doing and why. I created this solution using an actual selection sort algorithm because I wasn't sure if you wanted the selection sort you mention in the topic or the bubble sort you provided. So I wrote it with the idea that you could drop in a bubblesort if you needed by replacing the function and making sure it takes an array and returns a sorted array.

Now I am not a big fan of changing a person's program all around more than need be to get a solution. In sticking with this mentality, I tried to build on what you had implemented already like using charAt() and primitive datatype arrays etc. One place where this gets sticky is when converting a charAt over to the integer value needed for sorting appropriately. I pass the char to the valueOf to get it to a string that I could then use in a parseInt to make sure it was an integer. The solution works out nicely, but it looks funny doing it.

So here is the solution...

CODE

import java.io.*;
import java.util.*;


public class String1 {

    public static Scanner con = new Scanner(System.in);

    // Main program start point.
    public static void main(String [] args) {
        int length;

        System.out.println("Input a string of letters and numbers:");
        String str = con.next();

        length = str.length();

        process(str,length);
    }


    // Process the entered input and determine if it is a number.
    public static void process (String str1, int length1)
    {
        int i = 0, numbercount = 0;
        int[] numbers = new int[length1];

        // Initialize entire array with invalid value
        for(int f = 0; f < numbers.length; f++) {
                numbers[f] = -1;
        }

        for (i=0; i<length1; i++)
        {
                // If number, convert it to an integer to store
                if(Character.isDigit(str1.charAt(i))) {
                        numbers[numbercount] = Integer.parseInt(String.valueOf(str1.charAt(i)));
                        numbercount++;
                }        
        }

        // Sort the array and store it in new sorted array
        int[] sortednumbers;
        sortednumbers = selectionSort(numbers);

        // Now print it
        printArray(sortednumbers);
        System.out.println();

    }


    // This is a custom selection sort, but you could easily make it bubble
    // by making sure it takes an integer array and returns a sorted array.

    private static int[] selectionSort(int[] numArray) {
        for (int i = 0; i < numArray.length - 1; i++) {
            for (int j = i + 1; j < numArray.length; j++) {
                    if (numArray[i] > numArray[j]) {
                        int swap = numArray[i];
                        numArray[i] = numArray[j];
                        numArray[j] = swap;
                    }
            }
        }
        return numArray;
    }


    // This function loops through our sorted numbers and prints
    // only those elements which are numbers

    private static void printArray(int[] printArray) {
        String result = "";
        for (int i = 0; i < printArray.length; i++) {
                if (printArray[i] > -1) {
                        if (result.equals("")) {
                                result += printArray[i];
                        }
                        else { result += ", " + printArray[i]; }
                }
        }

        System.out.println("Sorted Numbers: " + result);

    }    
}


One thing I want to point out is the use of the -1 value in the array to mark invalid array entries. I look for this in the print to know if I have actually have a legit value in the array since the selection sort will push all legit values to the end of the array. I could reverse the sort order in the algorithm, but not knowing if you are going to change it later I didn't bother.

To make a more elegant solution I would have considered using an ArrayList or implement a Linked List so that I didn't have to loop through the entire array looking for valid entries. I again wasn't sure how far along you were and if you had experience in those solutions. So I opted for the more basic way.

Hope you find this solution ok since it does what you want, modify it whatever way you like.

decap.gif


excellent solution, however I find checking values (case select style) much easier. or you could to a if statement to pull out the numbers from the string.
i know this is just psudocode, but i'm not writing it for you.
CODE

if the substring(i) of str = 1 then put in strNum
else if the substring(i) of str = 2 then put in strNum
.
.
.
else if the substring(i) of str = 0 then put in strNum

this would be in a for loop that increases i each time until it finishes str
in other words
CODE

for(int i == 0; i <= str.length(); i++)
{
}

you could also shorten the if statement by putting or's, but it may go off screen.
CODE

if the substring(i) of str = 1 or the substring(i) of str = 2 or...the substring(i) of str = 0
then put in strNum

then run the sort and you should be good to go.
blink.gif that's alot of writing! good luck! biggrin.gif icon_up.gif
User is offlineProfile CardPM
+Quote Post

Martyr2
RE: User-defined Method With String And Selection Sort
21 Aug, 2007 - 01:38 PM
Post #4

Programming Theoretician
Group Icon

Joined: 18 Apr, 2007
Posts: 5,655



Thanked: 313 times
Expert In: C/C++, Java, VB, VB.NET, C#, PHP, Web Development, HTML & CSS, Javascript

My Contributions
Well while your solution will work it is a bit cumbersome and presents a lot of repeat code. The trickiness I mention is that you have to make sure you can convert to the proper data types to guarantee a good sort. Being that he was using charAt() was the cause of many problems. I would try and avoid using select statements testing individual chars, numbers etc in such a situation when a loop can do such a comparison fast and efficiently and usually more compact. It also provides an easier way of modification later rather than introducing a new case. Such a select case can seem small at first, but over time they can grow into something monsterous. smile.gif


User is offlineProfile CardPM
+Quote Post

Fast ReplyReply to this topicStart new topic
Time is now: 1/8/09 12:35AM

Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter

Live Java Help!

Java Tutorials

Reference Sheets

Java Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month