user-defined method with string and selection sort

output numbers in the string in ascending order using selection sort (

Page 1 of 1

3 Replies - 4456 Views - Last Post: 21 August 2007 - 02:38 PM Rate Topic: -----

#1 jei_monsterkid  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 05-July 07

user-defined method with string and selection sort

Posted 21 August 2007 - 01:29 AM

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:
/*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:

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..

Is This A Good Question/Topic? 0
  • +

Replies To: user-defined method with string and selection sort

#2 Martyr2  Icon User is online

  • Programming Theoretician
  • member icon

Reputation: 4308
  • View blog
  • Posts: 12,088
  • Joined: 18-April 07

Re: user-defined method with string and selection sort

Posted 21 August 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...

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.

:snap:

This post has been edited by Martyr2: 21 August 2007 - 11:54 AM

Was This Post Helpful? 0
  • +
  • -

#3 goingse  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 3
  • Joined: 26-July 07

Re: user-defined method with string and selection sort

Posted 21 August 2007 - 12:22 PM

View PostMartyr2, on 21 Aug, 2007 - 11:53 AM, said:

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...

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.

:snap:


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.
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
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.
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: that's alot of writing! good luck! :D :^:
Was This Post Helpful? 0
  • +
  • -

#4 Martyr2  Icon User is online

  • Programming Theoretician
  • member icon

Reputation: 4308
  • View blog
  • Posts: 12,088
  • Joined: 18-April 07

Re: user-defined method with string and selection sort

Posted 21 August 2007 - 02:38 PM

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. :)
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1