Array Sorting getting error [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
class arr{
//array sorting to find maximum value
public static void main(String[]args){
int[] array={1,6,4,5,2};
int n;
int i,j;
for( i=0;i<(array.length*2);i++){
for( j=0;j<array.length;j++){
if(array[j]>array[j+1]){
array[j]=array[j+1];
array[j+1]=array[j];
}
}
}
System.out.println(array[array.length]);
}
}
>
Can anyone tell me why i am getting runtime error and this sorting method will work or not?

Dont reinvent the wheel.., you are able to use arrays, so then use the array help class too...
:-)
public static void main(String[] args) {
final int[] array = { 1, 6, 4, 5, 2 };
System.out.println("Array before sort " + Arrays.toString(array));
Arrays.sort(array);
System.out.println("Array before sort " + Arrays.toString(array));
}

you will likely have an indexOutOfbounds exception because your second loop:
for( j=0;j<array.length;j++){
if(array[j]>array[j+1]){
array[j]=array[j+1];
array[j+1]=array[j];
}
}
J loops through teh array then you attempt to index the array at J + 1 which on the last element in the array would push it out of bounds thus throwing an outOfBoundsException

for( j=0;j<array.length;j++){
if(array[j]>array[j+1]){
array[j]=array[j+1];
array[j+1]=array[j];
}
}
Since array.length = 5 and j < array.length, the value array[j+1] in the last round of the inner loop cause array out of bound exception.
The swap needs another variable to hold array[j] before changing it.
e.g:
int x;
for( j=0;j<array.length - 1;j++){
if(array[j]>array[j+1]){
x = array[j];
array[j]=array[j+1];
array[j+1]=x;
}
}

The bubble sort algorithm can be implemented as follows
public static void sort(int[] arr){
int len = arr.length;
int k = 0;
for(int j = 0 ; j < len-1; j++){
for(int i= 0+k; i < len-1; i += 2){
if(arr[i] <= arr[i+1])
continue;
int tmp = arr[i];
arr[i] = arr[i+1];
arr[i+1] = tmp;
}
k++;
if ( k % 2 == 0)
k = 0;
} }
The inner loop must alternately start at indexes 0 and 1 so as not to always swap the same pairs (k variable).
The others have already pointed out why you're getting an exception.

Related

Reordering numbers in an array [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I am trying to solve a leetcode problem :
Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements.
Example:
Input: [0,1,0,3,12]
Output: [1,3,12,0,0]
And I think I have the correct solution but I'm just not sure why I'm getting it incorrect.
class Solution {
public void moveZeroes(int[] nums) {
for (int i = 0; i > nums.length;i++) {
int j= i;
while ((j<nums.length) && (nums[j]==0)){
j++;
}
if (j<nums.length){
nums[i]=nums[j];
nums[j]=0;
}
}
}
}
You can solve this problem O(N) with one pointer. This'd pass through:
public class Solution {
public static void moveZeroes(int[] nums) {
if (nums == null || nums.length == 0)
return;
int pos = 0;
for (int num : nums)
if (num != 0)
nums[pos++] = num;
while (pos < nums.length)
nums[pos++] = 0;
}
}
References
For additional details, you can see the Discussion Board. There are plenty of accepted solutions with a variety of languages and explanations, efficient algorithms, as well as asymptotic time/space complexity analysis1, 2 in there.
The for loop isn't correct (has to be i < nums.length), also, your solution doesn't work if there is nothing to do:
final int[] expectedArray = {1,2,0,0};
final String expectedString = Arrays.toString(expectedArray);
int[] nothingToDo = {1,2,0,0};
moveZeroes(nothingToDo);
assertEquals(expectedString, Arrays.toString(nothingToDo));
yields in:
org.junit.ComparisonFailure: expected:<[[1, 2], 0, 0]> but was:<[[0, 0], 0, 0]>
Just write some test cases yourself and see what's wrong.
In your case:
if (j<nums.length){
nums[i]=nums[j];
nums[j]=0;
}
is wrong because you're swapping i with j, even if i == j and nums[i] != 0.
Since I don't think you're asking for a working solution, I won't provide one. But here are my test cases:
#Test
public void testEmptyArray() {
int[] array = new int[0];
moveZeroes(array);
assertEquals(0,array.length);
}
#Test
public void testZeroOnlyArrays() {
int[] array = {0,0,0,0};
final String arrayString = Arrays.toString(array);
moveZeroes(array);
assertEquals(arrayString, Arrays.toString(array));;
}
#Test
public void mixedTest() {
int[] array = {0,1,0,2};
final int[] expectedArray = {1,2,0,0};
final String expectedString = Arrays.toString(expectedArray);
moveZeroes(array);
assertEquals(expectedString, Arrays.toString(array));;
int[] nothingToDo = {1,2,0,0};
moveZeroes(nothingToDo);
assertEquals(expectedString, Arrays.toString(nothingToDo));
}
The 'for' loop should be: for (int i = 0; i < nums.length;i++)
then, your loop will run on the array indexes from 0 until it reaches the length of the array.
The current code will not even enter the loop as you have defined i=0 and the loop condition is run the loop only if it is larger than the array size: (i > nums.length) which of course is not true
You are using i > nums.length that's why loop is not executed
You need an index for non-zero value. Here in my solution j is for non-zero value index means when you find a non-zero value set j index and increment it. If j is smaller than i or equal that's means there will be zero found then set it.
public void moveZeroes(int[] nums) {
int j = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] != 0) {
nums[j] = nums[i];
j++;
}
if (j <= i) {
nums[i] = 0;
}
}
}

Array's methods and comands [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I was trying to obtain the minimun value and its index between an array of int.
I can't understand why if I use the for-loop inside the main method it doesn't work, but if I use the same code in an aux method it works. The code should be right.
The part of the code that is commented is the for-loop that doesn't work.
package minimoArray;
import java.util.Scanner;
public class minimoArray {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Inserisci 10 numeri interi: ");
int [] Arr = new int [10];
//int a = Arr[0];
int b = 0;
for (int i = 0; i < Arr.length; i++) { //NON si può riempire l'array con for-each
Arr[i] = scanner.nextInt();
}
/*
for (int i = 0; i < Arr.length; i++) {
if (Arr[i] < a) {
a = Arr[i];
b = i;
}
}*/
int minimo = minimo(Arr);
for (int i = 0; i < Arr.length; i++) {
if (Arr[i] == minimo) {
b = i;
}
}
System.out.println(" il minimo è: " + minimo);
System.out.println(" l'indice del minimo è: " + b);
}
private static int minimo (int [] a) {
var min = a[0];
for (int i = 1; i < a.length; i++) {
if (a[i] < min ) {
min = a[i];
}
}
return min;
}
}
Edit: Just saw that the a is commented out too, my mistake. However, here Nicktar's answer applies with the reason why, you set a to the first element of the array, whose numbers weren't even set yet. The solution stays the same though.
First of all, stick to the naming convention of Java. Classes start with an uppercase letter, variables start with a lowercase letter.
Your mistake in the for loop within your main method is that a isn't even definied there, therefore the whole loop shouldn't even compile.
Simply add the var a = Arr[0]; before the loop and start the loop at the index 1.
The initialization of a in your main method is to early. You set a to Arr[0] before the array is written which sets it to 0 because primitive int is initalized to 0. So your code in the main methods compares all your array to 0.... This would find a minimum that is negative only.

Why does this sort in Java not work? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I'm trying to implement a short sorting algorithm, but it simply doesn't work. Anyone with more experience in programming got any tips? The array is not sorted, several values are coming up multiple times in the end print. Why?
public static void main(String[] args) {
// Sort the data
int[] array = {1,5,2,3,6,2,29,-2,23,3};
for (int i = 0; i<array.length-1; i++) {
if (array[i] > array[i+1]) {
array[i+1] = array[i];
array[i] = array[i+1];
}
}
// Print the data.
for (int i = 0; i<array.length; i++) {
System.out.print(i+ ", ");
}
}
Your swap is broken. After you call array[i+1] = array[i];, array[i] = array[i+1]; does nothing because array[i+1] is overwritten. You need to store the value in a temporary variable:
int temp = array[i+1];
array[i+1] = array[i];
array[i] = temp;
Here:
array[i+1] = array[i];
array[i] = array[i+1];
You must store the value in a temporary variable, as in the second line you get the same value.
Try with this
int tmp = array[i];
array[i] = array[i+1];
array[i+1] = tmp;
Several points. See if below helps :
There should be few compilation problems - semi colon missing, trying length() on array than length.2. In the end, you simply print i from 0 to array length. I suppose you want to print array[i]. 3. There are multiple sorting algorithm which you can find by googling.4. If you choose bubble sort, try with two loops, one outer till length of array and one inner, till (array length-elements already sorted). And inside you compare using temp variable.
temp = array[j];
array[j] = array[j+1];
array[j+1] = temp;
1 if you want to swap two element please use temporary variable
public void swap(int[] nums,int i,int j)
{ int tmp=nums][i];
nums[i]=nums[j];
nums[j]=tmp;
}
2 this way which you display can't sort the data, here is my way to sort data:
public void insertionSort(int nums[])
{
int j;
for(int i=1,i<nums.length-1;i++){
int tmp=nums[i];
for(j=i;j>0&&nums[j]<nums[j-1];j--)
nums[j]=nums[j-1];
nums[j]=tmp;
}
}
you need to add temporel variable and return to the start of array after every swap
public static void main(String[] args) {
// Sort the data
int[] array = {1,5,2,3,6,2,29,-2,23,3};
int temp;
for (int i = 0; i<array.length-1; i++) {
if (array[i] > array[i+1]) {
temp=array[i+1]; //temporel
array[i+1] = array[i];
array[i] = temp;
i=0; //to return to the start of the array
}
}
// Print the data.
for (int i = 0; i<array.length; i++) {
System.out.print(i+ ", ");
}
}

how to print number of occurences of element of an 1d array [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I have worked on this but I keep getting an exception. Can anyone tell me where the problem is?
package assingment;
public class frequencyCount {
static void count(int x[]){
System.out.println("ENTERED ARRAY IS ");
for( int i=0; i < x.length; i++)
{
System.out.print(x[i]);
}
int c[] = new int [x.length];
for(int i=0; i<c.length ;i++)
{ c[i] = 0;
}
for(int i=0; i< x.length ;i++){
int m= x[i];
c[m]++;
}
System.out.println("frequency table");
for(int i=0; i< c.length ;i++){
System.out.print(i + " "+ c[i]);
}
}
public static void main(String[] args) {
count(new int []{1,1,5,2,10});
}
}
This is because you are incorrectly allocating the space to store your counts properly. What you need is to create an array where the total number of elements is the maximum of your array, plus 1 to account for 0. I'm going to assume that all of your numbers are positive to make things simple. As such, you actually need to determine what the maximum value is in your array first, then allocate the space accordingly.
By not doing this, when you specify the value of 5 in your array, you only allocated an array of size 5, and so if you try using 5 to index into your array, you get an OutOfBounds exception as you are trying to access the sixth position of the array, where it doesn't exist.
FWIW, there are much more smarter ways to do this, such as using a HashMap, but I'm assuming you haven't covered more advanced data structures in your Java course yet, and you probably need a solution with arrays. However, I completely recommend using HashMap.
As such, modify your code to find the maximum first, then allocate accordingly:
package assingment;
public class frequencyCount {
static void count(int x[]){
System.out.println("ENTERED ARRAY IS ");
// NEW - To store maximum
int maxi = -1;
for( int i=0; i < x.length; i++)
{
System.out.println(x[i]);
// Keep checking for the maximum
if (x[i] > maxi)
maxi = x[i];
}
// NEW - modify length to account for maximum
int c[] = new int [maxi+1];
for(int i=0; i<c.length ;i++)
{
c[i] = 0;
}
for(int i=0; i< x.length ;i++){
int m= x[i];
c[m]++;
}
System.out.println("frequency table");
for(int i=0; i< c.length ;i++){
System.out.println(i + " "+ c[i]);
}
}
public static void main(String[] args) {
count(new int []{1,1,5,2,10});
}
}
You are trying to access c[m] where m=x[i] in 3rd cycle. But x[2]=5 and c[5] causes an exception since there are only 5 elements in c[] (from c[0] to c[4])

set even to 0 and odd to 1

I'm playing around with double arrays and am trying to set all the even elements of an array to 0 and all of the odd elements of the array to 1. Everything looks okay to me, but when I run it I get a bunch of errors. Not sure what's wrong; I've been looking at it for a while with no luck. Any advice on how to fix the errors it gives would be great, thanks!
Code:
public class SetOf0and1 {
public static void main(String[]args)
{
int [][] numbers1 = {{4,2,5}, {2,4,1}, {1,3}};
System.out.println("Before setting elements between 0 and 1: ");
displayArray(numbers1);
setEvenRowsTo0OddRowsTo1 (numbers1);
System.out.println("After setting the elements between 0 and 1");
displayArray(numbers1);
}
public static void setEvenRowsTo0OddRowsTo1(int [][]array)
{
for(int i=0; i<array.length;i++)
{
for(int j=0; j<array[i].length;j++)
{
if(i%2 == 0)
array[i][j]=0;
else
array[i][j]=1;
}
}
}
public static void displayArray(int [][]array)
{
for(int i=0;i<array.length;i++)
{
for( int j=0; j<array.length;j++)
{
System.out.println(array[i][j] + " " );
}
System.out.println();
}
}
}
Errors given:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
at SetOf0and1.displayArray(SetOf0and1.java:38)
at SetOf0and1.main(SetOf0and1.java:10)
public static void displayArray(int [][]array)
{
for(int i=0;i<array.length;i++)
{
for( int j=0; j<array.length;j++)
^^^^^^^^^
{
System.out.println(array[i][j] + " " );
}
System.out.println();
}
Your inner loop should stop at array[i].length.
In the method displayArray, the line:
for( int j=0; j<array.length;j++)
Should be:
for( int j=0; j<array[i].length;j++)
array.length does not return the length you thing it does! You have a 2 dimentional array. So if we say you have array[x][y] then array.length will be x and array[i].length (for 0 <= i < x) will be y. This could be different depending on the length of the array on that index. (so the formula does not exactly apply like that)
int [][] numbers1 = {{4,2,5}, {2,4,1}, {1,3}};
this statement initializes an array with three arrays of the legthes 3, 3 and 2!!!
(in the third block you have only two elements !!! - {1,3})
In your displayArray-method you use two times ...
array.length
... to distinct the size of the loop
that sets the number of loops to 3 ... But last block is only two elements long -> errror.
Use this instead for the second loop:
for( int j=0; j<array[i].length;j++)
If you want to check if a number is odd, you can do it this way:
int answer = thenumber % 2;
'thenumber' is the integer to check if it is even.
Then 'answer' would be 0 if the number was even.
And if you want to loop through the array and do it:
for (int i = 0; i < numbers1.length(); i++)
{
if (numbers1[i] % 2 == 0) {
//EVEN
numbers1[i] = 0;
}
else if (numbers1[i] % 2 == 1) {
//ODD
numbers1[i] = 1;
}
}
And, even more compact:
for (int i = 0; i < numbers1.length(); i++)
{
numbers1[i] %= 2;
}
Edit: I forgot that it was an array you had! I was thinking about ArrayList! Fixed.

Categories

Resources