Java Insertion Sort doesnt sort - java

I have written a java sorting algorithm by insertion, the code compiles but doesnt sort:(. If anyone could point out any flaws, Id be very thankful, Java doesnt...
public class Sort {
public static int[] sort(int[] x) {
int[] y = new int[x.length];
for(int i = 0; i < x.length; ++i) {
int j = 0;
while (y[j] < x[i] && j < i) ++j;
for (int k = i-1; k >= j; --k) y[k+1] = y[k];
y[j]=x[i];
}
return y;
}
public static void main(String[] args) {
int[] size = new int[10];
for(int k=0; k<size.length; ++k ) {
size[k]=(int)(Math.random()*20);
System.out.println(size[k]);
}
System.out.println(sort(size));
}}

[I#39ed3c8d is returned by invoking toString() on an int array, which you then print with System.out.println.
You presumably want System.out.println(Arrays.toString(sort(size))); instead.

You are printing the reference of size i.e., [I#39ed3c8d .
This should help you to understand:
public class Sort {
public static int[] sort(int[] x) {
int[] y = new int[x.length];
for(int i = 0; i < x.length; ++i) {
int j = 0;
while (y[j] < x[i] && j < i) ++j;
for (int k = i-1; k >= j; --k) y[k+1] = y[k];
y[j]=x[i];
}
return y;
}
public static void main(String[] args) {
int[] size = new int[10];
System.out.println("Befor sorting");
for(int k=0; k<size.length; ++k ) {
size[k]=(int)(Math.random()*20);
System.out.print(size[k]);
System.out.print(" ");
}
size = sort(size);
System.out.println("\nAfter sorting");
for(int i = 0; i<size.length; i++){
System.out.print(size[i]);
System.out.print(" ");
}
}}

That random is result of:
System.out.println(sort(size));
Do this instead:
size = sort(size);
for(int k=0; k<size.length; ++k ) {
System.out.print(size[k] + " " );
}

Related

Filling an array with random elements and using SelectionSort but getting weird error: Fix?

class SelectionSort {
public static int[] sort(int[] arr, int n) {
//int min;
int temp;
for(int i=1; i < n; i++) {
int min = i;
for (int j = i+1; j <= n; j++)
if (arr[j] < arr[min])
min = j;
temp = arr[i];
arr[i] = arr[min];
arr[min] = temp;
}
return arr;
}
public static int[] fillArray(int[] arr) {
for (int k=0; k < arr.length; k++) {
arr[k] = (int)(Math.random() * 100);
System.out.println(arr[k] + " ");
}
return arr;
}
public static void main(String args[]) {
/* SelectionSort ob = new SelectionSort();
int n = 100;
int[] arr = new int[n];
ob.sort(arr);
ob.fillArray(arr); */
int[] arr1 = fillArray(arr1);
int[] arr2 = sort(arr1);
for (int i:arr2) {
System.out.print(i);
}
}
}
I am getting an odd error saying 'SelectionSort.java:31: error: method sort in class SelectionSort cannot be applied to given types;', any ideas how to fix this? i'm lost.
In the inner for loop you have put "j <= n"
for (int j = i+1; j <= n; j++){
So j become size of the array, but max index should be 1 less than n.

Ragged array not showing all averages

It only prints out the average to the first column but doesn't do anything for the next.
it only prints out 717, for the first column average. It is a ragged array. Everything else compiles fine.
import java.util.Scanner;
import java.io.*;
public class Fitness
{
public static void main(String [] args)
{
int [][] week = {{800,1000,100},{450,100,845,20,1200,200},{1800,250,400},{0,1500,800,120},{600,500},{700,1400,1700,100},{675}};
System.out.println("Average over 7 days");
avgCalb(week);
static void avgCalb(int [][] x)
{
for(int j = 0; j < x[0].length; j++)
{
int colTotal = 0;
for(int i = 0; i < x.length; i++)
{
colTotal = colTotal + x[i][j];
}
System.out.println(colTotal/7);
break;
}
}
}
summing columns
static void avgCalb(int [][] x)
{
int[] colTotal = new int[x.length];
for(int j = 0; j < x.length; j++)
{
for(int i = 0; i < x[j].length; i++)
{
colTotal[i] += x[j][i]
}
}
for(int i = 0;i<colTotal.length;i++) {
System.out.println((double)colTotal[i]/colTotal.length);
}
}
summing rows
static void avgCalb(int [][] x)
{
for(int j = 0; j < x.length; j++)
{
int colTotal = 0;
for(int i = 0; i < x[j].length; i++)
{
colTotal += x[j][i];
}
System.out.println(colTotal/x[j].length);
}
}

java.lang.ArrayIndexOutOfBoundsException Error

How do I fix this error and what does it mean?
java.lang.ArrayIndexOutOfBoundsException: 5
at Sort.sort(Sort.java:29)
at Sort.<init>(Sort.java:13)
at SortedArray.<init>(SortedArray.java:23)
Here is the code:
import java.util.Scanner;
import java.util.Random;
public class SortedArray
{
Scanner input = new Scanner(System.in);
int [] Array;
Sort sortedArray;
int sizeOfArray;
public SortedArray()
{
System.out.print("Enter the number of values to put in the array: ");
sizeOfArray = input.nextInt();
Array = new int [sizeOfArray];
System.out.println("");
for(int i = 0; i < sizeOfArray; i++)
{
Random r = new Random();
Array[i] = r.nextInt(100) + 1;
System.out.println(Array[i]);
}
sortedArray = new Sort(Array, sizeOfArray);
sortedArray.display();
}
}
public class Sort
{
int[] array;
int sizeOfArray;
public Sort(int[] oldArray, int sizeOfOldArray)
{
sizeOfArray = sizeOfOldArray;
array = new int [sizeOfArray];
for( int i = 0; i < sizeOfArray; i++)
{
array[i] = oldArray[i];
}
sort();
}
public void display()
{
for ( int i = 0; i < sizeOfArray; i++){
System.out.println(array[i]);
}
}
private void sort()
{
for (int i = 0; i < sizeOfArray; i++)
{
for (int j = 0; j < sizeOfArray; i++)
{
if (array[j] < array[i])
{
swap(i,j);
}
}
}
}
private void swap(int x, int y)
{
int temp;
temp = array[x];
array[x] = array[y];
array[y] = temp;
}
}
I get the error when I run the program and enter the value. The program is supposed to sort the numbers from greatest to least. I'm not sure what is wrong.
First, what it means: you have an array and are trying to acces an index that is outside its range (below 0 or bigger or equal than the length of the array).
The probable cause is:
for (int j = 0; j < sizeOfArray; i++)
Notice that you check that j does not get too big but you are increasing i.
The Problem is that the inner loop also incrementsi which isn't correct in this situation!
private void sort()
{
for (int i = 0; i < sizeOfArray; i++)
{
for (int j = 0; j < sizeOfArray; j++)
{
if (array[j] < array[i])
{
swap(i,j);
}
}
}
}
Your problem is on this line
for (int j = 0; j < sizeOfArray; i++)
it should be
for (int j = 0; j < sizeOfArray; j++)

How Can I Display a N x N Matrix of Random Numbers in Java?

I'm trying to create a matrix of random double numbers. The matrix must be of size n x n and all numbers must be between 1 and 100. I've been trying to sort it out for ages now and I know it must be something so simple (as it usually is).
Here is my code:
public static void main(String[] args) {
PrintRandomGraph(RandomArray(4));
}
private static double[] RandomArray(int n) {
double[] randomArray = new double[n];
double[][] randomMatrix = new double [n][n];
Random rand = new Random();
rand.setSeed(System.currentTimeMillis());
for (int i = 0; i < n; i++) {
Integer r = rand.nextInt()% 100;
randomArray[i] = Math.abs(r);
for (int j = 0; j < n; j++) {
Arrays.fill(randomMatrix, i, i+1, randomArray);
}
}
return randomArray;
}
private static void PrintRandomGraph(double[] inputArray) {
int n = inputArray.length;
double[] showArray = new double[n];
double[][] showMatrix = new double [n][n];
for (int j = 0; j < n; j++) {
for (int i = 0; i < n; i++) {
double r = inputArray[i];
showArray[i] = r;
Arrays.fill(showMatrix, i, i+1, showArray);
}
}
System.out.println(Arrays.deepToString(showMatrix));
}
When I run the code I get a random array repeated n times like :
[[63.0, 97.0, 64.0, 75.0], [63.0, 97.0, 64.0, 75.0], [63.0, 97.0, 64.0, 75.0], [63.0, 97.0, 64.0, 75.0]]
I think I need to go back to the top of the for loop and add the new array...? Please help =(
Any help is much appreciated. Thank you.
Did you try something like this:
private static double[][] RandomArray(int n) {
double[][] randomMatrix = new double [n][n];
Random rand = new Random();
rand.setSeed(System.currentTimeMillis());
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
Integer r = rand.nextInt()% 100;
randomMatrix[i][j] = Math.abs(r);
}
}
return randomMatrix;
}
to Print the graph:
public void printGraph(double[][] array, int n) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.println(array[i][j]);
}
}
}
To Print Graph with Square brackets:
public void printGraph(double[][] array, int n) {
for (int i = 0; i < n; i++) {
System.out.print(" [ ");
for (int j = 0; j < n; j++) {
System.out.print(array[i][j]);
}
//Put println instead of print here to have each row in a new line
System.out.print(" ]");
}
}
Also, this seems a lot like homework, if it is, please tag it like so :)
Hi all this provides the answer I was looking for
private static double[][] RandomArray(int n) {
double[][] randomMatrix = new double [n][n];
double[] randomArray = new double [n];
Random rand = new Random();
rand.setSeed(System.currentTimeMillis());
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
Integer r = rand.nextInt()% 100;
randomMatrix[i][j] = Math.abs(r);
}
}
return randomMatrix;
}
public static void main(String[] args){
//PrintRandomGraph(RandomArray(5));
System.out.println(Arrays.deepToString(RandomArray(5)));
}

2d ArrayList in Java adding data

I need little help on a homework assignment. I have to create a 10 by 10 ArrayList, not an array. This is what I have and I just need a hint on how to do a for loop to add the date to the 2D ArrayList. By the way this is for putting data that are grades; going from 100 to 82. (Yes I know it is homework but need to be pointed in the correct direction)
public void q6()
{
//part a
ArrayList<ArrayList<Double>> grades;
//part b
grades = new ArrayList<ArrayList<Double>>(10);
//second dimension
grades.add(new ArrayList<Double>(10));
for(int i = 0; i < 10; i++)
{
for(int j = 0; j < 10; j++)
{
// grades.get().add(); Not sure what to do here?
// If this was an array I would do something like:
// grades[i][j] = 100 -j -i;
}
}
}
Something like this could do?
public void q6()
{
//part a
ArrayList<ArrayList<Double>> grades;
//part b
grades = new ArrayList<ArrayList<Double>>(10);
//second dimension
for(int i = 0; i < 10; i++)
{
List<Double> current = new ArrayList<Double>(10);
grades.add(current);
for(int j = 0; j < 10; j++)
{
current.add(100 - j - i);
}
}
}
Given the code, all you left to do is change it a little to receive 10x10 matrix.
public class Main
{
public static final int ROW_COUNT = 5;
public static final int COL_COUNT = 10;
public static void main(String[] args)
{
ArrayList<ArrayList<Double>> grades = new ArrayList<ArrayList<Double>>();
for (int i = 0; i < ROW_COUNT; i++)
{
ArrayList<Double> row = new ArrayList<Double>();
for (int j = 0; j < COL_COUNT; j++)
{
row.add(100.0 - j - i);
}
grades.add(row);
}
for (int i = 0; i < ROW_COUNT; i++)
{
for (int j = 0; j < COL_COUNT; j++)
{
System.out.print(grades.get(i).get(j));
System.out.print(", ");
}
System.out.println("");
}
}
}

Categories

Resources