Java: Increment operation not working inside if block - java

I am writing a small code for bubble sort using Java as below
package raja.programming.bubblesort;
public class Main {
public static void main(String[] args) {
// write your code here
//int[] intArray = {5, -10, 22, 43, 1, 17};
int[] intArray = { 20, 35, -15, 7, 55, 1, -22 };
for ( int unsortedArrayIndex = intArray.length -1 ; unsortedArrayIndex > 0 ; unsortedArrayIndex--){
for ( int index = 0 ; index < unsortedArrayIndex ; index++){
System.out.println("index " + intArray[index] + " index+1 : " + intArray[index+1] );
if ( intArray[index] > intArray[index+1]) {
swap(intArray, index, index+1);
}
}
}
for (int num: intArray) {
System.out.println(num);
}
}
public static void swap( int[] array, int i, int j) {
if ( i == j) {
return ;
}
System.out.println("swap index " + array[i] + " index+1 : " + array[j] );
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
In the line if ( intArray[index] > intArray[index+1]) { I am passing as index+1 then only my code working, if I pass i++ or ++i its not working.
What is the reason behind this behaviour, please help me understand?
Thank you.

When you use index + 1 your code compares the element at the position index and the one at the position index +1 and the loop adds 1 at the end of the instuctions inside the loop
But if you use ++i or i++ your code will do the same thing but the index you used will jump by 2 the incrementation of the for loop and the incrementation you did.
it will not work if you do i++ beacuse this will increment i and return the previous value of i before incrementing so it's like you compare the element to itself
But if you use ++i it will increment the value of i and return the value incremented. But in both ways, in one loop, you increment i twice. If you really want to use either of those you need to remove the for loop and use a while loop and use ++i

i think the reason is. if u are using an index i for example and u increment it inside the loop, u will jump the next iteration. i++ is equals to i = i+1, but i+1 is not equals to i=i+1

You are iterating using index, when you are referring the position in an array using index + 1then the value ofindex` variable is not changed.
But if you use index++ or ++index, then you are incrementing the value of the index variable by 1 in that iteration and you will be skipping one index. Because of the same reason, the output array you are getting is unsorted in this case.

Related

find the range over a incline

goodday i am having an issue with my code. i am trying to iterate over an arraylist and see for which indices the values are increasing.
lines = [5, 7, 10, 11, 8, 6, 5, 4, 7, 8]
for (int i = 0; i < lines.size(); i++) { //iterate over array
// System.out.println(lines.get(i) + " ");
if (i == 9){
break;
}else if (lines.get(i) < lines.get(i + 1)){
System.out.println((i) + "-" + (i+1));
}else {
continue;
}
}
and my output produces this:
0-1
1-2
2-3
7-8
8-9
however i want my output to look like this:
0-3
7-9
You print directly after the if presence.
You would have to add another query after the first if. Something like this should solve the problem
`for (int i = 0; i < lines.size(); i++) { //iterate over array
// System.out.println(lines.get(i) + " ");
if (i == 9){
break;
}else if (lines.get(i) < lines.get(i + 1)){
if(lines.get(i) > lines.get(i+1){
System.out.println((i) + "-" + (i+1));
}
}else {
continue;
}
}`
You are printing every line, so it is expected the output is moving unit by unit.
What you can do is create a boolean that is initially set to false. Then, it will be set to true if the condition lines.get(i) < lines.get(i + 1) is true, and store the index i.
It will then change to false again whenever the condition lines.get(i) < lines.get(i + 1) is not true. Store the index again and only then print.
Trivial solution:
private static void compare( int start, int end )
{
if( start != end )
{
System.out.println( start + " - " + end );
}
}
public static void main(String args[]) {
int[] lines = { 5, 7, 10, 11, 8, 6, 5, 4, 7, 8 };
int start = 0;
for( int i = 0; i < lines.length - 1; i++ )
{
if( lines[i] >= lines[i + 1] )
{
compare( start, i );
start = i + 1;
}
}
compare( start, lines.length - 1 );
}
This can very likely be further optimized.
The code in your question is not a minimal, reproducible example so I understand that lines is a List. However you are accessing it as if it were an array so in the code, below, I used an array of int rather than a list of Integer.
The best way to understand how the code works is to run it through a debugger. If you are using an IDE, like IntelliJ or Eclipse, then it has a debugger.
Alternatively do a walk through of the code and write down the values of the variables as they change. This is known as debugging by hand.
int[] lines = new int[]{5, 7, 10, 11, 8, 6, 5, 4, 7, 8};
int end = lines.length - 1;
int lower = 0;
int upper = 0;
for (int i = 0; i < end; i++) { // iterate over array
if (lines[i] < lines[i + 1]) {
if (lower == upper) {
lower = i;
}
upper = i + 1;
}
else {
if (upper > lower) {
System.out.println(lower + "-" + upper);
}
lower = upper = i;
}
}
if (upper > lower) {
System.out.println(lower + "-" + upper);
}
The limit of the for loop must be one less than the size of the array, otherwise the lines[i + 1], on the last iteration of the loop, will be greater than the index of the last element in lines and that will cause an exception to be thrown.
After the for loop terminates, you need to check the values of lower and upper to see whether the last elements of lines are increasing. Hence the if statement after the for loop.
When I run the above code I get the following output:
0-3
7-9
I understand that this is your desired output.
Although you are working in Java this is more of an algorithm question than something specific to the language.
You'll need to keep track of the beginning of an incline as an independent variable. This is initially null because you do not know if the ArrayList begins with an incline or decline (or steady?). Since you want to keep track of the indexes, you'll need to iterate via the index - which you're already doing.
You are iterating from 1. This makes sense as it allows you to compare the current with the previous. Remove the break on the index 9 - this will cripple your algorithm if the number of elements varies. You should not make assumptions that the data your instructor will test with will be the same as the sample provided. They will look for edge cases that break a naive algorithm.
On a given iteration there are four possible states
you were on an incline and it continues through index
you were on an incline but it ended at previous index
you were not on an incline but you incline from previous index to index
you were not on an incline and you are not incling from previous index to index
There are only two cases where you do something - when you either begin or end an incline. Note that the List may end on an incline so you need to check for that case after completing the iteration. This has the distinct odor of a class assignment so I'm not going to provide Java code but the follow pseudocode describes the general algorithm.
let beginning-of-incline be null
for each index starting with 1
let inclining = is there an incline from the previous element to this element
if inclining and beginning-of-incline is null
capture beginning-of-incline
else if not-inclining and beginning-of-incline is not null
record incline from beginning-of-incline to previous index
clear beginning-of-incline
end-if-else
end for-each-index
if beginning-of-incline is not null
record incline from beginning-of-incline to final index of ArrayList
endif

Bubble sort swap method clarification

Ive been following a course that goes over bubble sort but one part of the swap method implementation has been bothering me. The part that doesnt make sense to me and hoping someone can clarify has to do with the comparison regarding the index.
public static void main(String[] args) {
int[] intArray = {20, 35, -15, 7, 55, 1, -22};
//start at index 6 which is -22 value; as long as the length of the array is more than 0; decrement down to the first index
for (int lastUnsortedIndex = intArray.length -1; lastUnsortedIndex > 0; lastUnsortedIndex -- ){
//i=0; as long as i is less than length of intArray -1, so 6; i++
for(int i =0; i< lastUnsortedIndex; i++){
//if value at index i is more than value at index i+1
if(intArray[i] > intArray[i +1]){
//swap their positions
swap(intArray, i , i+1);
}
}
}
for(int num : intArray){
System.out.println(num);
}
}
//for swapping
public static void swap (int[] array , int i , int j){
System.out.println("i= "+i);
System.out.println("j= "+j);
if(i == j){ // if they are the same then just return
return;
}
int temp = array[i];// need the temporary variable to hold value at position i because
//... we are going to swap array[i] with j, but still need to retain the value so we can assign it to array[j]
array[i] = array[j];
array[j] = temp;
}
As you can see if(i == j){return;} seems to only be comparing the index if im not mistaken. Why even bother doing this check? Doesnt seem like i will ever equal i+1, unless I'm missing something here?
There's no reason to do the check. It's also pointless to pass i+1 to swap. Just pass i, and replace j with i+1 everywhere. Don't worry about checking for equality. Remove the print statements if you care about speed.

Unsorted didgit in Insertion Sort Algorithm

// this describes the insertion sort algorithm
public class InsertionSort {
public static void main(String[] args) {
//array of unsorted integers
int [] array = { 10, 4, 1, 11, 5, 3, 8, 2, 0, 9};
int n = array.length;
for ( int j = 1; j<n; j++) {
//assign a value to the second element in the array
int key = array[j];
//assign a value to the 1st element in the list
int i = j-1;
//loop executes as long as i>0 and that the element befor the key is greater than the key itself
while( i>0 && array[i]>key) {
//move the bigger element 1 block forward
array[i+1] = array[i];
// keep moving until the element is in the right position
i =i-1;
}
array[i+1] = key;//assign the key to the appropritae location
}
for (int i=0; i<n; i++)
System.out.print(array[i] + " ");
System.out.println();
}
}
this is the ouput, As you can see, everything is sorted besides 10, which is still out of place in the array
10 0 1 2 3 4 5 8 9 11
This line has a problem:
while( i>0 && array[i]>key) {
The first iteration, j equals 1 and so i equals 0. And your loop doesn't run, because 0 is not greater than zero. But it should run, so the condition needs to change to "greater than or equals zero":
while( i>=0 && array[i]>key) {
That will fix your sort.

Finding how many times an item Appears in an Array

Given an array of integers ranging from 1 to 60, i'm attempting to find how many times the numbers 1-44 appear in the array. Here is my method
public static void mostPopular(int[] list, int count)
{
int[] numbers;
numbers = new int[44];
for (int i = 0; i<count;i++)
{
if (list[i]<45 )
{
numbers[i-1]=numbers[i-1]+1; //error here
}
}
for (int k=0; k<44;k++)
{
System.out.println("Number " + k + " occurs " + numbers[k-1]+ "times");
}
}
I'm trying to iterate through the array, list, that contains over 5000 numbers that are between 1-60, then test if that number is less than 45 making it a number of interest to me, then if the integer is 7 for example it would increment numbers[6] By 1. list is the array of numbers and count is how many total numbers there are in the array. I keep getting an ArrayIndexOutOfBoundsException. How do I go about fixing this?
Replace this line numbers[i-1]=numbers[i-1]+1;
with numbers[list[i] - 1] = numbers[list[i] - 1] + 1;
Now it will update the count of correct element.
You need to increment numbers[list[i]] because that's your value which is smaller than 45. i goes up to 5000 and your array numbers is too small.
You should really start using a debugger. All the modern IDE have support for it (Eclipse, IntelliJ, Netbeans, etc.). With the debugger you would have realized the mistake very quickly.
If your initial value is less than 45, it will add 1 to numbers[i-1]. However, since you start with i=0, it will try to add 1 to the value located at numbers[-1], which doesn't exist by law of arrays. Change i to start at 1 and you should be okay.
Very close, but a few indexing errors, remember 0-1 = -1, which isn't an available index. Also, this isn't c, so you can call list.length to get the size of the list.
Try this (you can ignore the stuff outside of the mostPopular method):
class Tester{
public static void main(String args[]){
int[] list = new int[1000];
Random random = new Random();
for(int i=0; i<list.length; i++){
list[i] = random.nextInt(60) + 1;
}
mostPopular(list);
}
public static void mostPopular(int[] list)
{
int[] numbers = new int[44];
for (int i = 0; i< list.length ;i++)
{
int currentInt = list[i];
if(currentInt<45 )
{
numbers[currentInt - 1] = (numbers[currentInt -1] + 1);
}
}
for (int k=0; k<numbers.length; k++)
{
System.out.println("Number " + (k+1) + " occurs " + numbers[k]+ "times");
}
}
}
When i is 0, i-1 is -1 -- an invalid index. I think that you want the value from list to be index into numbers. Additionally, valid indices run from 0 through 43 for an array of length 44. Try an array of length 45, so you have valid indices 0 through 44.
numbers = new int[45];
and
if (list[i] < 45)
{
// Use the value of `list` as an index into `numbers`.
numbers[list[i]] = numbers[list[i]] + 1;
}
numbers[i-1]=numbers[i-1]+1; //error here
change to
numbers[list[i]-1] += 1;
as list[i]-1 because your number[0] store the frequency of 1 and so on.
we increase the corresponding array element with index equal to the list value minus 1
public static void mostPopular(int[] list, int count)
{
int[] numbers = new int[44];
for (int i = 0; i<count;i++)
{
//in case your list value has value less than 1
if ( (list[i]<45) && (list[i]>0) )
{
//resolve error
numbers[list[i]-1] += 1;
}
}
//k should start from 1 but not 0 because we don't have index of -1
//k < 44 change to k <= 44 because now our index is 0 to 43 with [k-1]
for (int k=1; k <= 44;k++)
{
System.out.println("Number " + k + " occurs " + numbers[k-1]+ "times");
}
}

why does the index increases before looping

I cannot figure out why the for loop counter increases before I want it too / before it executes the entire for-loop block. I have littered the code with print statements for debugging, here is the code:
public void findSubSeq() {
temp = new ArrayList<Integer>();
temp.add(vals.get(0));
for (int i = 0; i < (vals.size()-2); i++) {
System.out.println(i + " index in array, for");
if (vals.get(i) < vals.get(i++)) {
System.out.println(i + " index in array, if 1");
temp.add(vals.get(i++));
System.out.println(i + " index in array, if 2");
System.out.println(this.getlargest());
}
else {
System.out.println(i + " index in array, else 1");
compareALs();
System.out.println(i + " index in array, else 2");
temp.add(vals.get(i++));
System.out.println(i + " index in array, else 3");
System.out.println(this.getlargest());
}
}
}
In the run of the code we can see that the counter i increases before the end of the for-loop. I am really confused. I have also tried a for-each loop with similar results.
Here is the run:
before subarrayB creation
before fillAL
Input file: inp
[1, 2, 3, 0, 4, 5]
before findSubSeq
0 index in array, for
1 index in array, else 1
1 index in array, else 2
2 index in array, else 3
[1]
3 index in array, for
4 index in array, else 1
4 index in array, else 2
5 index in array, else 3
[1]
You have vals.get(i++) which increments i. When used this way, ++ is a postincrement operator.
You really need to avoid using i++ inside the loop. That is what is causing your index variable to get incremented when you don't expect it. For example, your code does this:
if (vals.get(i) < vals.get(i++))
I think you really want to do this:
if (vals.get(i) < vals.get(i+1))
Similarly, when you add to temp, you really don't want to do i++, you want:
temp.add(vals.get(i+1));
if (vals.get(i) < vals.get(i++))
statement is like x < x, because increment accrues after get calling.
Use
if (vals.get(i) < vals.get(++i))
If you want to compare i-th and i+1 th elements.
The second: you have 3 increments of i in one cycle in one case by i. One in for cycle, the second in if and the 3-d, in add. Is it that which you planned?

Categories

Resources