I'm having some trouble sorting an array. I'm trying to sort it in ascending order.
My task is to get a series of integers from the user and store them into an array, then display them back to the user in ascending order. I was fine getting input from the user, storing it in the array and displaying them back. I was able to run my code and get the results I wanted but as far as getting the integers in the array in ascending order using selection sort, I was having a lot of difficulty with that.
The size of the array depends on the value that the user inputs, so it is set to the variable numValues rather than a number.
I get an error with the sort method I created. I'm getting syntax errors and void is an invalid type. I think I'm missing something and I'm not sure how to go about fixing this. If someone can point me in the right direction. Any help would be appreciated.
System.out.println("Here are the values you've entered" );
for(int n=0; n<values.length; n++)
{
System.out.print(values[n] + "");
}
System.out.println("Here are the values you've entered, in ascending order");
/*
* Method to arrange values in ascending order
*/
private static void sort(int[] values) {
int scan;
int index;
int minIndex;
int minValue; // Variables to put values in ascending order
for(scan=0; scan < (values.length-1); scan++)
{
minIndex = scan;
minValue = values[scan];
for(index = scan+1; index < values.length; index++)
{
if(values[index] < minValue)
{
minValue = values[index];
minIndex = index;
} // End if
} //End for
values[minIndex] = values[scan];
values[scan] = minValue;
} // End for loop
/*
* For loop to display values
*/
for(int n=0; n < values.length; n++ )
{
System.out.print(values[scan] + " ");
} //End for
} // End method sort
keyboard.close(); // To close Scanner object
} //End method main
You cannot have another method inside main. Get the method sort(int[] values) out of main, and call it inside main.
You had another problem. Inside your sort method:
System.out.print(values[scan] + " ");
scan has to be replaced by n.
Here is the completed code:
import java.util.*;
public class Project {
public static void main(String[] args) {
int numValues; // The number of values user has
int [] values; // Array declaration for values
Scanner keyboard = new Scanner(System.in); // Scanner object to get input from user
System.out.println("How many values do you have?"); // To get number of values for array
numValues = keyboard.nextInt();
/*
* Array to hold number of values
*/
values = new int [numValues];
/*
* Loop to gather integer values
*/
for (int n=0; n < values.length; n++ )
{
System.out.print("Enter value " + (n+1) + ":" );
values[n] = keyboard.nextInt();
} //End for loop
System.out.println("Here are the values you've entered" );
for(int n=0; n<values.length; n++)
{
System.out.print(values[n] + " ");
}
System.out.println("Here are the values you've entered, in ascending order");
sort(values);
keyboard.close(); // To close Scanner object
}
/*
* Method to arrange values in ascending order
*/
private static void sort(int[] values) {
int scan;
int index;
int minIndex;
int minValue; // Variables to put values in ascending order
for(scan=0; scan < (values.length-1); scan++)
{
minIndex = scan;
minValue = values[scan];
for(index = scan+1; index < values.length; index++)
{
if(values[index] < minValue)
{
minValue = values[index];
minIndex = index;
} // End if
} //End for
values[minIndex] = values[scan];
values[scan] = minValue;
} // End for loop
/*
* For loop to display values
*/
for(int n=0; n < values.length; n++ )
{
System.out.print(values[n] + " ");
} //End for
} // End method sort
} // End class Project
Your program will not executed or will not display correct result due to some reasons.
You are using "private static void sort(int[] values)" method in main method and it's not possible because we can't define method in another method. Either you have to create a separate method outside of main method or you can use sorting functionality in your main method also.
Another mistake is in below code. You are using scan variable for displaying result in ascending order. Here is should be n.
for(int n=0; n < values.length; n++ )
{
System.out.print(values[scan] + " ");
}
Your logic is correct. But it's little bit large for selection sort. Below is small way to do this.
public class SelectionSort
{
public static void main(String[]args)
{
int [] values = {15,14,13,12,11};
System.out.println("Here are the values you've entered" );
for(int n=0; n<values.length; n++)
{
System.out.print(values[n] + "");
}
System.out.println("\nHere are the values you've entered, in ascending order");
sort(values);
}
private static void sort(int[] values)
{
int index = 0;
int index2 = 0;
int temp = 0;
for(index=0; index<values.length; index++)
{
for(index2 = index+1; index2< values.length; index2++)
{
if(values[index] > values[index2])
{
temp = values[index];
values[index]= values[index2];
values[index2] = temp;
}
}
}
for(int n=0; n < values.length; n++ )
{
System.out.print(values[n] + " ");
}
}
}
int[] arrayToSort=new int[]{1,7,81,2,-2,9,9,6,-6};
//the outer loop will switch the number
for(int i=0;i<arrayToSort.length;i++){
int indexSmal=i;
//the inner loop will search for the biggest number
for(int j=i+1;j<arrayToSort.length;j++){
//search for biggest number index starting from i index
if(arrayToSort[j]>arrayToSort[indexSmal]){
indexSmal=j;
}
}//end loop
//swap the number
int smallNum=arrayToSort[indexSmal];
arrayToSort[indexSmal]=arrayToSort[i];
arrayToSort[i]=smallNum;
}// end loop
for(int i=0;i<arrayToSort.length;i++){
System.out.print(arrayToSort[i]+", ");
}
Related
I'm pretty sure I've done most of the code correctly but I'm returning the wrong thing? I've tried using copyOf() but still had the same issue. It looks like I'm returning the object of an array rather than the elements? I need the method treble to return the original array repeated in order, three times in one array. So [1,2,3,] should look like [1,2,3,1,2,3,1,2,3] when trebled.
Any help would be much appreciated.
import java.util.Scanner;
import java.util.Arrays;
public class ArrayExercises
{
public static void main(String[] args)
{
final int SIZE = 5;
int[] array = new int[SIZE];
Scanner scanner = new Scanner(System.in);
for (int i = 0; i < array.length; i++)
{
System.out.print("Please enter whole number " + (i + 1) + ": ");
int input = scanner.nextInt(); // get input from the user
array[i] = input; // store the value in the array
}
printArray("Input array:", array);
// call method sum and print out the result
int sum = sum(array);
System.out.println("The sum of elements is " + sum);
// call method repeat and print out the result
int[] trebled = repeat(array);
System.out.println("The repeated array is " + trebled);
}
public static void printArray(String msg, int[] array)
{
System.out.println(msg + " " + Arrays.toString(array));
}
public static int sum(int[] array)
{
int s = 0;
for (int i = 0; i < array.length; i++)
s += array[i];
return s;
}
public static int[] repeat(int[] array) //this is the part I'm having trouble with
{
int len = array.length;
int[] multiplied = new int[len*3];
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < len; j++)
{
multiplied[i * len + j] = array[j];
}
}
return multiplied;}
}
Try using:
System.out.println("The repeated array is " + Arrays.toString(trebled));
to print your array instead of printing using the array variable name, because otherwise that will print the address of the array rather than the content.
your method is ok, the issue is how you print it because as mentioned in the comments you do not use your printArray() method in this case.
So try changing this line :
System.out.println("The repeated array is " + trebled);
to :
printArray("The repeated array is " , trebled);
import java.util.ArrayList;
import java.util.Random;
public class Sorting
{
public static int numOfComps = 0,
numOfSwaps = 0;
public static void main(String[] args)
{
System.out.println("\nOriginal order:");
int size = 5;
ArrayList<Integer> list = new ArrayList<Integer>(size);
for(int i = 1; i <= size; i++)
{
list.add(i);
}
Random rand = new Random();
while(list.size() > 0)
{
int index = rand.nextInt(list.size());
System.out.print(list.remove(index) + " ");
}
System.out.println();
int[] test = convertIntegers(list);
int[] a = new int[5];
// Selection Sort
System.out.println("\n\nSelection Sort");
// Display copy of random generated number original order
System.out.println("\nOriginal order:");
System.arraycopy(test, 0, a, 0, test.length);
System.out.println(a + " ");
// Selection Sort method
selectionSort(a);
System.out.println("\nSorted order: ");
for(int element : a)
System.out.print(element + " ");
}
public static int[] convertIntegers(ArrayList<Integer> integers)
{
int[] num = new int[integers.size()];
for (int i=0; i < num.length; i++)
{
num[i] = integers.get(i).intValue();
}
return num;
}
public static void selectionSort(int[] array)
{
int startScan; // Starting position of the scan
int index; // To hold a subscript value
int minIndex; // Element with smallest value in the scan
int minValue; // The smallest value found in the scan
// The outer loop iterates once for each element in the
// array. The startScan variable marks the position where
// the scan should begin.
for (startScan = 0; startScan < (array.length-1); startScan++)
{
// Assume the first element in the scannable area
// is the smallest value.
minIndex = startScan;
minValue = array[startScan];
// Scan the array, starting at the 2nd element in
// the scannable area. We are looking for the smallest
// value in the scannable area.
for(index = startScan + 1; index < array.length; index++)
{
if (array[index] < minValue)
{
minValue = array[index];
minIndex = index;
}
// Counts the number of values comparisons
numOfComps ++;
}
// Counts the number of values swaps
if(minIndex != startScan)
{
numOfSwaps ++;
}
// Swap the element with the smallest value
// with the first element in the scannable area.
array[minIndex] = array[startScan];
array[startScan] = minValue;
}
System.out.println("\nNumber of comps = " + numOfComps);
System.out.println("Number of swaps = " + numOfSwaps);
}
}
How do I write code to copy random generated numbers to the selection sort method so that the random generated numbers can be displayed as an exact copy under the displayed heading "Selection Sort" as well as displaying the number of comparisons and swaps, and the sorted order? The code I have provided is not working properly. Thank you for any help.
for(int i = 0; i< arr.length; i++){
//generate random number here and assign to arr[i]
}
enter code here
now add another for loop to display everything inside the array, then if you want to see if it works sort it then use another loop.
So I was tasked with asking the user to input 10 numbers into an array and then printing the numbers in order and reverse order using a tester class and not just the main.
I'm having problems with how to return the array that has been passed. Here's my code so far:
public class PrintIt
{
static int[] numbers = new int[10];
static int i = 0;
public static int PrintOrder()
{
System.out.println("\nList of numbers in order: \n");
for (int i = 0; i < numbers.length; i++)
{
System.out.println(numbers[i]);
}
return ;
}
public static int PrintReverse()
{
System.out.println("\nList of numbers in reverse order: \n");
for (int i = numbers.length - 1; i >= 0; i--)
{
System.out.println(numbers[i]);
}
return ;
}
}
and the tester class:
import java.util.Scanner;
public class PrintItTester
{
public static void main (String [] args)
{
Scanner input = new Scanner(System.in);
int i = 0;
int[] numbers = new int[10];
System.out.println("\nPlease input " + 10 + " numbers.");
for (i=0; i < numbers.length; i++)
{
PrintIt.numbers[i] = input.nextInt();
}
System.out.print(PrintIt.PrintOrder());
System.out.print(PrintIt.PrintReverse());
}
}
When I run the code with numbers[i] in the return it reads i as being 0 and only outputs the first element in the array. I've looked for a long time and I can't figure this out.
I know, obviously, that there needs to be something returned, but whatever I put doesn't work. For example, when I try to return the array, numbers[i], it only returns the first element because the variable has a value of 0.
You have several problems in your code:
The declaration int[] numbers = new int[10]; in the main is useless. Remove it, and replace numbers.length with PrintIt.numbers.length
Your methods return ints, not arrays. Make them void, and call them without System.out.print.
Remove the unnecessary return statements from the PrintOrder and PrintReverse methods.
This should fix the problem (demo).
I have two files that I am using for my Array median code. The first file( ArrayMedian.java) is used to collect and then calculate the median, the second file is the tester file ( ArrayMedianTest.java)
I was supplied with some source code and needed to modify it accept a set range for each number in the dataset. I got that part done and the random range displays, but now when I get to he array it no longer calculates, I really can't put my finger on what is going wrong.
Another thing I am trying to do is in the ArrayMedian, is put a while loop in there to make it terminate if a '0' is input for the dataset, but it does not seem to want to work in that file, could it be due to no main in the file?
package bonus2.u06.exercise.ex3;
import java.util.Scanner;
public class ArrayMedian {
private int[] arr; // just declare array
Scanner keyboard; // shared field
// initialize keyboard and array
public void init() {
keyboard = new Scanner( System.in );
System.out.print("Enter the dataset size: ");
int size = keyboard.nextInt(); // must be odd number
arr = new int[ size ]; // instantiate
}
// Randomize the array
public void getRange() {
//System.out.println("\nYou entered: ");
System.out.print("Enter a Range: ");
int range = keyboard.nextInt();
System.out.print("array: \n");
for(int i = 0; i < arr.length; i++){
int myRnd = (int)( range * Math.random() );
System.out.print(" " + myRnd + " ");
}
}
// find the median of array
public int calcMedian() {
int half_length = arr.length/2;
for (int i = 0; i < arr.length; i++) {
int count = 0;
for (int j = 0; j < arr.length; j++) {
if (arr[i] > arr[j])
count++;
}
if (count == half_length) {
//<========= terminate this method
return arr[i];
}
}
return 0;
}
}
ArrayMedianTest:
package bonus2.u06.exercise.ex3;
public class ArrayMedianTest {
public static void main(String args[]) {
// instantiate
ArrayMedian obj = new ArrayMedian();
// execute all methods
obj.init();
obj.getRange();
int median = obj.calcMedian();
System.out.println("\nmedian : " + median);
System.out.println("\n--- done ---");
}
}
Turn out, your algorithm works perfectly fine, except in the getRange() method, you forgot to set the values of the array, so the array is an array of zeros. Here is how it should look:
public void getRange() {
//System.out.println("\nYou entered: ");
System.out.print("Enter a Range: ");
int range = keyboard.nextInt();
System.out.print("array: \n");
for(int i = 0; i < arr.length; i++){
int myRnd = (int)( range * Math.random() );
System.out.print(" " + myRnd + " ");
arr[i] = myRnd; // <-- You missed this line right here!
}
}
Also, as a recomendation, if you want to put code in stackoverflow, it has to have a spacing of four at the begining of the line plus any indenting you might use. Good luck programming!
My task is to calculate the average of the Integers a user defines in an Array and print back to main using the method in my class file.
Currently I have both files to compile but can't seem to figure out why nothing is being printed. Please help, much appreciated!
Snippet of code in Test Program to examine:
// Print average of integers in array.
System.out.println("\nAverage of values in array =");
myArray.avgArray();
Snippet of code in Class Program to examine:
// Method to calculate average of integers in array.
public double avgArray()
{
int sum = 0;
for(int ctr = 0; ctr < limit; ctr++)
{
sum = sum + nrs[ctr];
}
double avg = sum /(double)limit;
return avg;
}
This code is my program for testing purposes:
import java.util.Scanner;
public class P5test
{
public static void main(String[] args)
{
// Set up Scanner object for keyboard input.
Scanner keyboard = new Scanner(System.in);
// Input size of array desired.
System.out.print("Size of array: ");
int size = keyboard.nextInt();
// Set up object.
P5class myArray = new P5class(size);
// Allow user to fill array.
System.out.println("\nEnter data for array:");
myArray.fillArray();
// Print contents of array.
System.out.println("\nContents of array:");
myArray.printArray();
// Print average of integers in array.
System.out.println("\nAverage of values in array =");
myArray.avgArray();
// Print postive values in array.
System.out.println("\nPositive values in array:");
myArray.pvaluesArray();
// Sort contents of array in ascending order.
System.out.println("\nSorted Array:");
myArray.sortArray();
myArray.printArray();
}
}
This code contains my class with the various methods I'll be implementing to main:
import java.util.Scanner;
public class P5class
{
// Constructor setting up empty array of size specified by user.
public P5class(int size)
{
limit = size;
nrs = new int[limit];
}
// Method to fill array.
public void fillArray()
{
// Set up Scanner object for keyboard input.
Scanner keyboard = new Scanner(System.in);
for(int ctr = 0; ctr < limit; ctr++)
{
System.out.print("Integer #" + (ctr+1) + ": ");
nrs[ctr] = keyboard.nextInt();
}
}
// Method to display contents of array.
public void printArray()
{
for(int ctr = 0; ctr < limit; ctr++)
{
System.out.println("Nrs[" + ctr + "] = " + nrs[ctr]);
}
}
// Method to calculate average of integers in array.
public double avgArray()
{
int sum = 0;
for(int ctr = 0; ctr < limit; ctr++)
{
sum = sum + nrs[ctr];
}
double avg = sum /(double)limit;
return avg;
}
// Method to examine if any positive values are present in array.
public void pvaluesArray()
{
int largest = nrs[0];
// Check to see if any other number in array is larger than first.
for(int ctr = 1; ctr < limit; ctr++)
{
if(nrs[ctr] > largest)
largest = nrs[ctr];
}
int sum = 0;
for(int ctr = 0; ctr < limit; ctr++)
{
sum = sum + nrs[ctr];
}
double average = (double)sum/limit;
for(int ctr = 0; ctr < limit; ctr++)
{
if(largest <= 0)
{
System.out.println("\nArray contains no positive integers.");
break;
}
else if (nrs[ctr] > 0)
{
System.out.println("Nrs[" + ctr + "] = " + nrs[ctr]);
}
}
}
// Method to sort array into ascending order.
public void sortArray()
{
for(int ctr0 = 0; ctr0 < limit-1; ctr0++)
{
// Make one pass of Bubble Sort.
for(int ctr = 0; ctr < limit-1; ctr++)
{
if(nrs[ctr] > nrs[ctr+1])
{
int temp = nrs[ctr];
nrs[ctr] = nrs[ctr+1];
nrs[ctr+1] = temp;
}
}
}
}
// Instance variables.
private int limit;
private int[] nrs;
}
Here is an example output of the program when Run:
----jGRASP exec: java P5test
Size of array: 5
Enter data for array:
Integer #1: 0
Integer #2: -9
Integer #3: 4
Integer #4: 7
Integer #5: 2
Contents of array:
Nrs[0] = 0
Nrs[1] = -9
Nrs[2] = 4
Nrs[3] = 7
Nrs[4] = 2
Average of values in array =
Positive values in array:
Nrs[2] = 4
Nrs[3] = 7
Nrs[4] = 2
Sorted Array:
Nrs[0] = -9
Nrs[1] = 0
Nrs[2] = 2
Nrs[3] = 4
Nrs[4] = 7
----jGRASP: operation complete.
It's returning a value, but you're not doing anything with it, try:
System.out.println("\nAverage of values in array = " + myArray.avgArray());
Or:
double avg = myArray.avgArray();
System.out.println("\nAverage of values in array = " + avg);
Or one of many other ways.
Or, instead of return avg;, you can simply print it out in the method with System.out.println(avg); and change the return type to void.