Selection Sort Method - Sorting Array And Return Result Of Each Step

Nov 20, 2014

This time I am having difficulties with selection sort method, but not with the method itself (I think). So I need to sort an array and return the result of each step.

This is the main code:

public class Functionality {
public static int[][] selctionsort(int[] a) {
for (int i=0; i<a.length; i++) {
int least = i;
for (int j=i+1; j<a.length; j++)

[Code] ....

And this is the Test folder:

import static org.junit.Assert.assertArrayEquals;
 public class PublicTests {
public static void main(String[] args) {
int[] a = new int[] { 35, 7, 63, 42, 24, 21 };
int[][] b = new int[][] { new int[] { 7, 35, 63, 42, 24, 21 },

[Code] ....

Now I am not sure what should I write in return since the 2nd (test) project has int[][] and in my main project I am working with int [].

View Replies


ADVERTISEMENT

Used Selection Sort Method On Array

Nov 11, 2014

I have a question about selection sort. If I had an array of numbers, 1 2 3 4 100 0, and used the selection sort method (below) on the array,would the 0 slowly work it's way down to the end?

Nest loop = full rotation of nest loop

Nest loop 1: 1 2 3 4 100 0
Nest loop 2: 1 2 3 4 100 0
Nest loop 3: 1 2 3 4 100 0
Nest loop 4: 1 2 3 4 100 0
Nest loop 5: 1 2 3 4 0 100
Nest loop 6: 1 2 3 0 4 100
etc.

METHOD:

static void selectionSort(int[] arr){
int n = arr.length;
for(int i = 0;i<n;i++){
int min = i;
for(int j = i+1;j<n;j++){
if(arr[j]<arr[min]){
min = j;
}
}
int temp = arr[i];
arr[i] = arr[min];
arr[min] = temp;
}
}

View Replies View Related

Selection Sort Method?

Mar 5, 2014

I'm trying to make a selection sort method that will sort a list of Strings alphabetically.

I have a test list of Strings like so:

Joe, Steve, Oscar, Drew, Evan, Brian, Ryan, Adam, Zachary, Jane, Doe, Susan, Fred, Billy-Bob, Cindy, Mildred, Joseph, Hammer, Hank, Dennis, Barbara

However, whenever I run the method, the element that should go last, Zachary, in this case, ends up getting moved to the front for some reason. I'm not sure why.

I tried changing what the first element was initialized to, to the variable i as that would logically work as well, but it ends up missing the first element in the list.

Java Code:

public static void selectionStringAscendingSort (String[] words){
int i, j, first;
String temp;
for ( i = 1; i < words.length; i++ ) {
first = 0; //initialize to subscript of first element
for(j = i; j < words.length; j ++){ //locate smallest element between positions 1 and i.
if( words[ j ].compareTo(words[ first ]) <0 )
first = j;
}
temp = words[ first ]; //swap smallest found with element in position i.
words[ first ] = words[ i ];
words[ i ] = temp;
System.out.println(Arrays.toString(words));
}
System.out.println(Arrays.toString(words));
} mh_sh_highlight_all('java');

View Replies View Related

Making Selection Sort Into A Recursive Method

Oct 21, 2014

How would I modify this version of a selection sort into a recursive method?

public static void selectionSortRecursive(Comparable [] list, int n)
{
int min;
Comparable temp;
for(int index =0; index < n-1; index++){
min = index;

[code]....

View Replies View Related

Graphic Array Selection Sort?

May 21, 2014

This is a lab for one of my CS classes, and the assignment is to create a randomly filled array (values 10-100) and use these values as the height of an array of rectangles (essentially a bar graph)that will be drawn on a page. After that's done, the code should use the selection sort method to sort the bars least to greatest, being repainted as it's sorted.

I'm receiving no errors, the original draws just fine, and the code sorts the first position and then...it just hangs. Like it's in an infinite loop but I have all of the modifiers in place (I think. I've been staring at this code for three days straight and I don't think I really see it anymore). I've tried talking to my professor and I get that her private life is really busy right now, but she just keeps blowing me off and I don't know what to do. Anyway, done with back story and whining so here's the code.

Rectangle class:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Rectangle

[code]....

View Replies View Related

Copying Random Generated Numbers To Selection Sort Method

Mar 19, 2015

Java Code:

import java.util.ArrayList;
import java.util.Random;
public class NumSorting {
public static int numOfComps = 0,
numOfSwaps = 0;
public static void main(String[] args)

[Code] ....

What is wrong with my code in this sorting program? It won't copy the random generated numbers to the sort method. How to get the random generated numbers to copy to the sort method. Below is what the program is displaying.

Original order : 3 2 5 4 1

Selection Sort

Original order:

[I@7a84e4

Number of comps = 10

Number of swaps = 0

Sorted order : 0 0 0 0 0

View Replies View Related

How To Use Selection Sort For Array From Smallest To Largest

Nov 19, 2014

I know it is possible to do this using the Array class but I don't want to use that. I am trying to use selection or bubble sort but I believe selection is what I want. This program asks the user to input 2 arrays with 10 integers each, sorts them from smallest to largest, then states whether they are the same or not. Comparing the two arrays.

import java.util.Scanner;
public class SetDifference
{
public static void main (String args[])
{
Scanner sc = new Scanner (System.in);
int array1[] = new int[10];
int array2[] = new int[10];

[Code] .....

View Replies View Related

How To Return Array From A Method / Back Into Main Method That Prints Out Stuff

May 27, 2014

I'd like to know how to return a new array, I wrote in a method below the main method. I want to print the array but system.out.print doesn't work for arrays apparently. What structure i should use?

View Replies View Related

Recursive Selection Sort

Oct 21, 2014

How would I modify this version of a selection sort into a recursive method?

public static void selectionSortRecursive(Comparable [] list, int n)
{
int min;
Comparable temp;

[code]....

View Replies View Related

Graphically Displaying Selection Sort

May 20, 2014

I am trying to write a program that graphically displays a selection sort. It needs to sort bars of various heights, and the bars heights are generated from an array of random integers. The program needs to show the bars swapping as they are being sorted, I am having trouble getting the bars to draw, it needs to look like a bar graph. Here is my code thus far (not counting my boiler plate):

import java.util.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.Timer;
import java.awt.*;
import java.util.Random;
public class SelectionSortPanel extends JPanel

[Code] ....

Also right now it is giving an error from the compareTo method?

View Replies View Related

How To Do Selection Sort Of ArrayList By Customer Last Name

Nov 8, 2014

I have an arrayList with these values:

Mike Smith with a customer id of 100 has an account number of 1000 and a balance of $5,000.00
Hank Jones with a customer id of 101 has an account number of 1001 and a balance of $45,000.00
Sam Overstreet with a customer id of 102 has an account number of 1002 and a balance of $45,000.00
Hank Jones with a customer id of 101 has an account number of 1003 and a balance of $48,000.00
and so on .....

I am trying to do a selection sort by the account holders last name. I understand how to do if the Arraylist holds integers, but my arraylist holds multiple fields. I am not allowed to use collections as this is a homework assignment.

here is the Account Class

public class Account implements Comparable<Account> {
private int acctNum;
private double balance;
private Customer cust; // note we are putting a Customer object in the Account clas
private static int nextAcct = 1000;// used to keep track of the next available account number

[Code] ....

View Replies View Related

Simple Selection Descending Sorting After Values Assigned

Oct 7, 2014

I am working on descending after I assign values. And everything is sorted, but one value. I don't know why always I get one value is not sorted.

public class SeunghunJunHw6 {
public static void main(String[] args){
double[] randomArray = new double[9];
//assign random double values between 0 to 100 but exclude 100
for(int i = 0; i<randomArray.length;i++){
randomArray[i] = Math.random()*100;

[Code] ....

View Replies View Related

Selection Sort / Binary Search And Recursion

Nov 26, 2014

Here is the code I have at the moment:

/**
* Use selection sort to sort the tracks by name. Return a new, sorted ArrayList of tracks.
*
* @return an ArrayList containing the tracks sorted by name, or null if no tracks exist
*/
public ArrayList<Track> getTracksSortedByName() {
// YOUR CODE HERE
if(tracks == null)
return tracks;

[Code] ....

Here are my 2 issues (there are 2 lines with compiler errors): I feel like I understand selection sort and binary search, but am not sure how to apply it to the more abstract idea of a Track ArrayList (hence the 2 compiler errors). What should I use to make it work. Lastly, I'm very uncomfortable with recursion, so my guess is there is also probably some logical issue with it in the getTracksSortedByName method.

View Replies View Related

Sorting Dates - Saving Result In Class

May 18, 2014

So, I have two classes (bubble sort and insert sort) which are sorting dates. I need to save their comparings and reallocation of elements.

And I don't know how to do it. The point is if I want save that dates(comparings and reallocation) to Result class i need to create new instances of class in each sorting classes so i can't later do something with that, because I have null in Main class.

To avoid that problem i have tried to make Result class as singleton.. I mean: "public static final Results INSTANCE = new Results();" and then in classes "static Results result = Results.INSTANCE" without constructor and to save for example comparings i had method:

Java Code:

int SetComparings(){
return comparings++;
} mh_sh_highlight_all('java');

But it do not work too, because it overwrites old dates. Is there anyway to do not create instance of class? I don't want to copy whole code because it is too long and cant be unreadable, but i will put you structure of my program:

Java Code:

class BubbleSort{}
class InsertSort{}
class Results{}
class Sorting{} // class with switch to choose which way of sorting use
public class Main{} mh_sh_highlight_all('java');

View Replies View Related

Error When Trying To Return Array Via Method

Jan 14, 2014

I am getting these errors with this code, I can not figure why this error is occuring.

what is the issue with this code?

Java Code: package ABC;
import java.util.ArrayList;
import java.util.Scanner;
public class GetInputFromUser {
private ArrayList<String> name = new ArrayList<String>();

[code]....

View Replies View Related

Method Must Return Int Type - If Given Integer Is Strong Return A / If Not Return B

Sep 7, 2014

I want to use a method, which takes for example an int and also returns an integer. For example, if the the given integer is strong return a, if it is notstrong return b. How would you write that in a Code?

I want to use that in a more general way. I want to give a method mlong the value X of the type date and let it return an int. Type date consists of 3 int, one of them is the int month.

mlong should return an int depending on the X.moth. at the moment my code looks like this:

// File1:
public class date {
public int day;
public int month;
public int year;
}

// File 2:
public class monthlength {
public int mlong(date X) {
int t;
t = X.month;
if (t == 1 || t == 3 || t == 5 || t == 7 || t == 8 || t == 10 || t == 12)
{ return 31; }
if(t == 4 || t == 6 || t == 9 || t == 11)
{return 30;}
}
}

View Replies View Related

Return Array Data From A Method Back To Main

Mar 16, 2014

I'm trying to return an array back to main. The array returned to main should contain the reversed random numbers array. I believe I have the array correctly reversed within the 'reverseArray' method. I'm trying to send this array back to main, but it appears to contain empty data (a bunch of zeros).

Java Code:

class ArrToMain {
public static void main(String[] args) {
final int NUMBER_OF_ELEMENTS = 1000;
double[] numbers = new double [NUMBER_OF_ELEMENTS];
//Invoke initialize method
initialize(numbers);

[Code] ......

View Replies View Related

JDBC SQLException - Statement Did Not Return Result Set

May 4, 2014

I get an Sqlexecption with this message "com.microsoft.sqlserver.jdbc.SQLServerException: The statement did not return a result set."

When I execute this query :

...
Statement stmt = conn.createStatement();
stmt.executeUpdate("IF EXISTS (SELECT name FROM master.sys.databases WHERE name = N'Repository')
"
                + "PRINT 'Database exists'

[Code] .....
 
I want to create a database and a table in sql server if it doesn't exist. How can i prevent this error.

View Replies View Related

Java Method - Return True If String Can Be Found As Element Of Array And False Otherwise

Mar 17, 2014

I am new to Java and would like to ask how to do this question specifically:

Code a Java method that accepts a String array and a String. The method should return true if the string can be found as an element of the array and false otherwise. Test your method by calling it from the main method which supplies its two parameters (no user input required). Use an array initialiser list to initialise the array you pass. Test thoroughly.

View Replies View Related

Program To Accept 10 Name In String And Sorting In Bubble Sort Alphabetically

Jun 10, 2014

import java.io.*;
Class bubble
{
public static void main()throws IOException
{
BuffetedReader br=new BufferedReader (new InputStreamReader (System.in));
int j, k, temp;
String st[]=new string [10];

[Code] .....

View Replies View Related

String Split Method - Return Array Of Strings Consisting Of Substrings Splitted By Delimiters

Sep 28, 2014

I am having a problem with the following code. It compiles and runs fine however my output is wrong.

public class SplitString {
public static void main(String[] args) {
String[] string1 = split("ab#12#453", "#");
String[] string2 = split("a?b?gf#e", "[?#]");
for (int i = 0; i < string1.length; i++) {
System.out.print(string1[i] + ",");

[code]....

The split method in the String class returns an array of strings consisting of the substrings split by the delimiters. However, the delimiters are not returned. Implement the following new method that returns an array of strings consisting of the substrings split by the matching delimiters, including the matching delimiters.public static String[] split(String s, String regex)For example, split("ab#12#453", "#") returns ab, #, 12, #, 453 in an array of String, and split("a?b?gf#e", "[?#]") returns a, b, ?, b, gf, #, and e in an array of String.

View Replies View Related

How To Return Values In Object Return Type Function (method)

Apr 2, 2014

How do i take input values for TwoDPoint (which are objects) and return it back in numerical values also print them.

When i create an object in main method and pass values to my function of return type TwoDPoint,it gives error:- found int,int need TwoDPoiint,TwoDPoint.

// Here is what i tried to do:

Created class TwoDPoint that contains two fields x, y which are of type int. Defined another class TestTwoDPoint, where a main method is defined.In the main method created two TwoDPoint objects.

Then I modified the class TestTwoDPoint and add another function to it. This function takes two TwoDPoints as input and returns the TwoDPoint that is farthest from the point (0,0).

Then I added another function to TestTwoDPoint. This function takes two TwoDPoints as input and returns a new TwoDPoint whose x value is the sum of x values of the input TwoDPoint's and whose y value is the sum of the y values of the input TwoDPoint's.

class TwoDPoint {
int x = 2;
int y = 4;
}
class TestTwoDPoint {
public static void main(String args[]) {
TwoDPoint obj1 = new TwoDPoint();
System.out.println(obj1.x);
System.out.println(obj1.y);

[Code] ....

View Replies View Related

User Input Random Numbers Then Program Sort Them In Different Ways - Missing Return Statement

Apr 7, 2014

I have been assigned to write a program that has a user input random numbers then the program is to sort them in different ways. I have the coding for the different sorts but, I have an error saying that I am missing a return statement in the "Bubble" method. I am trying to return "arr[i]" in the "for loop" which gives me this error, and when I try to take the "return arr[i]" outside of the "for()" loop the error reads the it cannot locate variable "i".

import java.awt.* ;
import java.awt.event.*;
import javax.swing.*;
public class SwingSorts extends JFrame implements ActionListener
{
JRadioButton bubble;
JRadioButton selection;

[Code] .....

View Replies View Related

How To Use Debugger To Step Though GUI Application

Feb 21, 2014

I am struggling with my current Java assignment and can't figure out how to use the debugger to step though a GUI application to see what exactly is happening where.

When I populate all fields in my GUI and they are validated successfully, the end message does not appear. Instead, in the console window, I get the following exception pointing to my printInvoice() method indicating a NullPointerException. As I said, everything has been filled out correctly and this program at least mostly-operated yesterday morning. Is there a way to find out where this is coming from using the message below?

Java Code:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at edu.witc.Ch_08_10ex2.controller.Hotel_Processor.printInvoice(Hotel_Processor.java:219)
at edu.witc.Ch_08_10ex2.controller.Hotel_Processor$SubmitButtonListener.actionPerformed(Hotel_Processor.java:61)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)

[code]....

View Replies View Related

Selection Of Invocation Of Overridden Method During Constructor Chaining

May 28, 2014

I don't understand, why when in the constructor of the superclass A the method init() is called (line 4), the overridden version of the subclass is invoked (line 26) and not the superclass version (line 7):

class A {
public A () {
init();
}
public void init() {
System.out.println("test");

[Code] ....

I would have guessed that above code prints

test
1

But instead you get a NPE (because when the constructor of B is invoked

public static void main(String[] args) {
new B();
}

Then there is first the implicit call to super:

public B() {
s = " ";
init();
}

Which is the constructor of A:

public A () {
init();
}

But here now this init() method is not the version of A ( public void init() {
System.out.println("test");
}) but the overriden version of the subclass (B): public void init() {
System.out.println(s+=s.length());
}...

Which throws an NPE of course, because the initialization of s has not occured yet (it happens only after the implicit call to super() has finished (see public B() {
s = " ";
init();
}))

View Replies View Related

How To Link Compress Method To Return Statement Method GetPText

Oct 30, 2014

Alright, I don't understand how to link my compress method to my return statement method "getPText". Also in my compression I only want it to compress for 3 or more consecutive letters.

import java.util.Scanner;
class RunLengthCode {
String pText;
String cText; 
void setPText(String PText) {
pText = "";
}

[Code]...

View Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved