Out of bounds exception when trying to run cocktail code java [duplicate] - java

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 3 years ago.
I am trying to make a cocktail sort but I am getting an out of bound exception at the line if (a[i] > a[i + 1]) and I'm not sure why.
Here is the full code. Sorry if this is completely wrong.
import java.util.Arrays;
import java.util.Scanner;
public class Cocktail
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int count = 0;
boolean switched = true;
int[]a = new int[10];
for (int i = 0; i < a.length; i++)
{
int value = input.nextInt();
a[i] = value;
}
System.out.println(a[0]);
while (switched == true)
{
switched = false;
for (int i = 0; i < a.length; i++)
{
if (a[i] > a[i + 1])
{
int temp = a[i];
a[i] = a[i + 1];
a[i + 1] = temp;
count++;
switched = true;
}
}
for (int i = a.length; i >= 0; i++)
{
if (a[i] > a[i + 1])
{
int temp = a[i];
a[i] = a[i + 1];
a[i + 1] = temp;
count++;
switched = true;
}
}
if (switched == false)
{
System.out.println(count);
}
}
}
}

you need to Change
if (a[i] > a[i + 1])to be like this --> if (i < a.length-1 && a[i] > a[i + 1]).
The problem was it is trying to reach the 11th element ;)
If you may, here's an Edited version of your code:
Scanner input = new Scanner(System.in);
int count = 0;
boolean switched = true;
int[]a = new int[10];
System.out.println("enter 10 Integers: ");// # Added to make code clearer
for (int i = 0; i < a.length; i++)
{
int value = input.nextInt();
a[i] = value;
}
System.out.println("thankyou, Sorting now!");//# also this one
while(switched == true)
{
switched = false;
for (int i = 0; i < a.length; i++)
{
if (i < a.length-1 && a[i] > a[i + 1]) // <-- # here was the problem
{
int temp = a[i];
a[i] = a[i + 1];
a[i + 1] = temp;
count++;
switched = true;
}
}
for (int i = a.length; i >= 0; i++)
{
if (i < a.length-1 && a[i] > a[i + 1]) //<-- # Also Here
{
int temp = a[i];
a[i] = a[i + 1];
a[i + 1] = temp;
count++;
switched = true;
}
}
if (switched == false)
{
System.out.println("count is "+ count);
}
}
// # added part to print array for testing
System.out.println("Sorted Array:");
for (int i = 0; i <a.length ; i++) {
System.out.print(a[i]+", ");
}
}//main
}//class
Here's the output:
Copy and paste it, Run and Happy Coding =D

Related

Array out of bounds in java but it worked in C [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
How dangerous is it to access an array out of bounds?
(12 answers)
Closed 5 years ago.
hey guys i am getting this error i did the same in C and it worked but when i did it in java i am getting the error "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5" can you look into this -->
import java.util.Scanner;
class sort {
public static void main(String args[]) {
Scanner obj = new Scanner(System.in);
int a[] = new int[5];
int i, j;
int temp;
System.out.println("Enter the elements of array : ");
for (i = 0; i < 5; i++) {
a[i] = obj.nextInt();
}
for (i = 0; i < 5; i++)
for (j = 0; j < 5; j++) {
if (a[i + 1] < a[i]) {
temp = a[i];
a[i] = a[i + 1];
a[i + 1] = temp;
}
}
for (i = 0; i < 5; i++)
System.out.println("\n" + a[i]);
}
}
Your problem is here:
for (i = 0; i < 5; i++)
for (j = 0; j < 5; j++) {
// When `i` == `4` this accesses `a[5]` which does not exist.
if (a[i + 1] < a[i]) {
It is ERROR in any language to access out-bounded array element.
eg, in C:
int a[1];
int tmp = a[5];
is WRONG (even if there is no crash or no execption)
so your java code is wrong, do NOT access any out-bounded element in any language.
buddy, you can't set i equal to or greater than 5 (indexes are 0 to 4)
so when it reach i == 4 in your second loop and you use a[i+1] you'll get an outOfBounException.
for (i = 0; i < 4; i++)
for (j = 0; j < 5; j++) {
if (a[i + 1] < a[i]) {
temp = a[i];
a[i] = a[i + 1];
a[i + 1] = temp;
}
}

Can not get precise results for the hourglass algorithm

Here is the link for definition of the hourglass problem:
https://www.hackerrank.com/challenges/30-2d-arrays
I wrote the following program:
package day11;
import java.util.Scanner;
public class Solution {
public static void main(String ... args){
Scanner scan = new Scanner(System.in);
int[][] arr = new int[6][6];
int maxHourGlassValue = 0;
int temp = 0;
int currMax = 0;
int k = 0, l = 0;
for(int i = 0 ; i < 6 ; i++){
for(int j = 0 ; j < 6 ; j++){
arr[i][j] = scan.nextInt();
}
}
for(int i = 1 ; i < 5 ; i++){
for(int j = 1 ; j < 5 ; j++){
if(maxHourGlassValue < currMax){
maxHourGlassValue = currMax;
}
}
}
System.out.println(maxHourGlassValue);
}
}
I could only run 6 out of 8 given test cases. What could possibly go wrong ????
Try this code, i did not write that code, i just copy it and modified it from here
import java.util.Scanner;
public class Test {
public static void main(String ... args){
Scanner scan = new Scanner(System.in);
int size = 6;
int[][] m = new int[size][size];
//numbers input
for(int i=0; i<size; i++)
{
for(int j=0; j<size; j++)
{
m[i][j] = scan.nextInt();
}
}
int temp = 0, MaxSum = -99999;
for (int i=0; i<size; ++i) {
for (int j=0; j<size; ++j) {
if (j+2 < size && i+2 < size) {
temp = m[i][j] + m[i][j+1] + m[i][j+2] + m[i+1][j+1] + m[i+2][j] + m[i+2][j+1] + m[i+2][j+2];
if (temp >= MaxSum) {
MaxSum = temp;
}
}
}
}
System.out.println(MaxSum);
}
}
Below is the code which will run successfully for all the test cases of hourglass problem.
public static void main(String[] args) {
try (Scanner scan = new Scanner(System.in)) {
int[][] arr = new int[6][6];
int maxHourGlassValue = -63;//Assigning (-9*7=)-63 which is the minimum possible value of "hourglass sum".
//Reading inputs.
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 6; j++) {
arr[i][j] = scan.nextInt();
}
}
//Logic.
/**
* Index of both i and j will run from 1 to 4 (one less than n-1 where n = 6)
* So for each i and j iteration calculating the sum of hourglass.
*/
int iHGValueTemp = 0;
for (int i = 1; i < 5; i++) {
for (int j = 1; j < 5; j++) {
iHGValueTemp = arr[i][j] + /*Main element*/
arr[i - 1][j - 1] + arr[i - 1][j] + arr[i - 1][j + 1]+ /*Top three elements of main element.*/
arr[i + 1][j - 1] + arr[i + 1][j] + arr[i + 1][j + 1]; /*Bottom three elements of main element.*/
if (iHGValueTemp > maxHourGlassValue) {
maxHourGlassValue = iHGValueTemp;
}
}
}
//Output.
System.out.println(maxHourGlassValue);
}
}
I have written description within code in the comments only. Please refer to that and discuss with me if any doubt.

Is my bubble sort and selection sort properly implemented?

Here is what I have for the bubble sort algorithm.
public void bubbleSort(int[] arr) {
boolean swapped = true;
int j = 0;
temp = 0;
while(swapped) {
swapped = false;
j++;
for(int i = 0; i < arr.length; i++) {
if (arr[i] > arr[i + 1]) {
temp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = temp;
swapped = true;
}
}
}
}
And for selection sort:
public int[] selectionSort(int[] arr) {
int i = 0;
int j = 0;
int minValue = 0;
int minIndex = 0;
int temp = 0;
for(i = 0; i < arr.length - j; j++) {
minValue = arr[i];
minIndex = i;
for(j = i; i < arr.length; j++) {
if (minValue < arr[i]) {
minValue = arr[j];
minIndex = j;
}
}
if (minValue < arr[i]) {
temp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = temp;
}
}
return arr;
}
Not sure about these implementations.
When I add a System.out.println(arr[i]); in there the numbers for bubble sort come out as:
4
3
2
1
3
2
1
2
1
1
[I#6d06d69c
When put at after the first if statement.
Now when I create a System.out.println(arr[i]); for selection sort it comes out as:
1
2
3
4
5
[I#6d06d69c
When put after the second if statement.
Thank you
There are a few bugs in your implementations which I have tried to correct.
public void bubbleSort(int[] arr) {
boolean swapped = true;
int j = 0;
temp = 0;
while(swapped) {
swapped = false;
j++;
for(int i = 0; i < arr.length-j; i++) {
if (arr[i] > arr[i + 1]) {
temp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = temp;
swapped = true;
}
}
}
}
public int[] selectionSort(int[] arr) {
int i = 0;
int j = 0;
int minValue = 0;
int minIndex = 0;
int temp = 0;
for(i = 0; i < arr.length - 1; i++) {
minValue = arr[i];
minIndex = i;
for(j = i+1; j < arr.length; j++) {
if (minValue < arr[j]) {
minValue = arr[j];
minIndex = j;
}
}
if (minValue < arr[i]) {
temp = arr[i];
arr[i] = minValue;
arr[minIndex] = temp;
}
}
return arr;
}

Array Index out of bounds exception, when I run this, I am not able to figure out why. I am not able to view the sorted array [duplicate]

This question already has answers here:
What is a stack trace, and how can I use it to debug my application errors?
(7 answers)
Closed 7 years ago.
import java.util.Scanner;
public class Sort {
public void Countsort(int a[], int b[], int k) throws ArrayIndexOutOfBoundsException {
int[] c = new int[k + 1];
for (int i = 0; i < k; i++) {
c[i] = 0;
}
for (int i = 0; i <= a.length; i++) {
c[a[i]] = c[a[i]] + 1;
}
for (int i = 1; i <= k; i++) {
c[i] = c[i] + c[i - 1];
}
for (int i = a.length; i <= 1; i--) {
b[c[a[i]]] = a[i];
c[a[i]] = c[a[i]] - 1;
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int num;
int[] temp = new int[10000];
int i = 0;
while (sc.hasNextInt()) {
num = sc.nextInt();
temp[i] = num;
i++;
if (num == -1) {
break;
}
}
int A[] = new int[i];
// just a check
for (i = 0; i < temp.length; i++) {
System.out.println("temp values:" + temp[i]);
}
// just a check ends
for (int j = 0; j < A.length; j++) {
A[j] = temp[j];
System.out.println("tem copied vals:" + A[j]);
}
// a check for gthat a has temp values..
int[] B = new int[A.length];
new Sort().Countsort(A, B, 100);
for (i = 0; i < B.length; i++) {
System.out.println("Run count #" + i + " : " + B[i]);
}
}
}
First of all your while loop should be
while (sc.hasNextInt()) {
num = sc.nextInt();
if (num == -1) {
break;
}
// so that you can stop -1 to be stored
temp[i] = num;
i++;
}
Next thing is your loop
for (int i = 0; i < a.length; i++) { // always less than length of the array
c[a[i]] = c[a[i]] + 1;
}

Why can't we change the order of statements in insertion sort's while loop?

As shown below is the basic insertion sort algorithm taught at school. if you change the order of while loop parameters, it doesn't work.
public static int[] insertionSort(int[] A){
for(int i =1; i<A.length;i++){
int key = A[i];
int j = i;
while(j>0&&A[j-1]>key){
A[j]=A[j-1];
j--;
}
A[j]=key;
}
return A;
}
After the change (Now the code wont work and it will give java.lang.ArrayIndexOutOfBoundsException: -1 expection):
public static int[] insertionSort(int[] A){
for(int i =1; i<A.length;i++){
int key = A[i];
int j = i;
while(A[j-1]>key&&j>0){
A[j]=A[j-1];
j--;
}
A[j]=key;
}
return A;
}
If there any other way to implement the same algorithm so that the order of the conditional loop statements doesn't matter?
Because of short-circuit evaluation.
If the first half of an && is false, the second half will not be evaluated at all (since the result cannot possibly be true).
Therefore, you can write j > 0 && A[j - 1]..., and A[j - 1] will only be evaluated if j > 0.
You can improve the above code as follow. Now the while loop will never fail for arr[-1] condition as every time j==-1 the loop will break out.
public static void InsertionSort()
int j, temp;
Scanner sc = new Scanner(System.in);
System.out.println("enter the size");
int n = sc.nextInt();
int arr[] = new int[n];
System.out.println("enter the elements");
for (int i = 0; i < n; i++)
{
arr[i] = sc.nextInt();
}
for (int i = 1; i < n; i++)
{
temp = arr[i];
j = i - 1;
while (arr[j] > temp && j >= 0)
{
arr[j + 1] = arr[j];
j = j - 1;
if (j == -1)
break;
}
arr[j + 1] = temp;
}
System.out.println("Array Sorted through Insertion Sort");
for (int i = 0; i < n; i++)
{
System.out.println(arr[i]);
}
}

Categories

Resources