I'm coding a Bubble Selection method, which should work with these credentials:
/* Write code for a Bubble Sort algorithm that starts at the right side of
* of ArrayList of Comparable objects and "bubbles" the largest item to the
* left of the list. The result should be an ArrayList arranged in descending
* order.
*/
#SuppressWarnings("unchecked")
void bubbleSort(ArrayList <Comparable> list) {
int end = list.size();
for (int i = 0 ; i < end; i++){
for (int j = end; j > 0; j--){
if ( list.get(j).compareTo(list.get(j-1)) > 0 ){
//swap
Comparable temp = list.get(j);
list.set(j,list.get(j - 1));
list.set(j - 1, temp);
//System.out.println(list);
}
}
end--;
}
}
The problem is, Java will then tell me it is out of bounds.
If I instead use
for (int j = end - 1; j > 0; j--)
the code will then run, however it does not run the number of times it needs to run for the list to completely finish sorting (aka it stops one loop ahead)
As explained, you need to start in end-1, or else you'll be accessing out of bounds of the array.
Let's say you have an array of integers: 5 1 4
Your algorith will do this:
1st iteration -> i = 0 / j starting at 2
1 5 4
2nd iteration -> i = 1 / j starting at 1
It will now only compare 5 and 1 and not switching them, because 5 is higher. So, and the 4 and 5? They should be swapped. Your algorithm implementation is wrong.
If you remove the end--; it should work.
However, this can be optimized
Use this code it will work for your requirement in array implementation where size is your array length.
for (int i = 0; i < size - 1; j++) {
for (int j = i + 1; j < size - 1; k++){
if (array[i] > array[j]) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
If the array is long 3, array[3] is out of bound.
Since you start with array[lenght] you have to decrement it before entering in the for cycle like the code you provide.
Using end - 1 will compare last and second last values in list
if you use end it will try to compare last value and value at index after last which will give ArrayOutOfBound Exception.
Now For correct output you have to remove end--; line as per shown below
for (int i = 0 ; i < end; i++){
for (int j = end -1; j > 0; j--){
if ( list.get(j).compareTo(list.get(j-1)) > 0 ){
//swap
Comparable temp = list.get(j);
list.set(j,list.get(j - 1));
list.set(j - 1, temp);
}
}
//remove below line
end--;
}
This will short the list by one value from right side also. So removing This will work
Related
Question :-
In the question we have to find the pivot index of the given array. And as per the given definition(given in the question) it is that point in the index such that if we calculate the sum of numbers on it's left and right they both comes out to be equal.
Example
Input: nums = [1,7,3,6,5,6]
Output: 3
Explanation:
The pivot index is 3.
Left sum = nums[0] + nums[1] + nums[2] = 1 + 7 + 3 = 11
Right sum = nums[4] + nums[5] = 5 + 6 = 11
My Approach and logic I tried
I calculate the total sum of array and then used a for loop to iterate from backwards in the array(from right to left) each time subtracting that element from total sum and comparing it to another loop which is calculating sum from right side such that when they get equal return that index element.
But I can't find the error
Code for the same
import java.util.*;
public class webs{
public static void main(String[] args){
int arr[] = {1, 7, 3, 6, 5, 6};
System.out.println(Calc(arr));
}
static int Calc(int arr[]){
int sum = 0;
int lsum = 0;
//this loop is for sum
for(int i =0; i < arr.length; i++){
sum += arr[i];
}
//this loop is for calculating sum from reverse
for(int j= arr.length - 1; j > 0; j--){
lsum += arr[j];
sum -= arr[j];
if(lsum == sum){
return arr[j];
}
else{
return -1;
}
}
return 0;
}
}
Please specify the error in this.
The for loop, in method Calc will only execute, at most, one iteration since it contains an if-else where both the if returns a value and the else returns a value. If you run your code with a debugger, you will discover that.
When I copied your code to my Eclipse, it warned me that the j-- part of the for loop is dead code. In other words it will never be executed because of the if-else statement in the loop body.
If lsum does not equal sum then you need to continue with the next loop iteration. Hence you need to remove the else.
Also, method Calc needs to return an index and not an element. Hence rather than
return arr[j];
you should
return j;
If the for loop terminates, that means that you did not find a pivot point and so the method should return -1 (negative one) and not zero. Hence the last line of method Calc should be
return -1;
Also, since you are iterating the array backwards, lsum should initially contain the sum of all the array elements and sum should be zero. In fact you either need to reverse sum and lsum or iterate the array forwards instead of backwards.
When iterating the array backwards, the terminating condition should be
j >= 0
and not
j > 0
because then you don't iterate the first element in the array.
Lastly, you need to adjust the value of sum after you test whether sum equals lsum.
Here is my rewrite of your code, containing the changes that I have described, above. I added print statements so you can [partially] see what is happening but as I said before, you need to learn how to debug your code.
static int Calc(int arr[]){
int sum = 0;
int lsum = 0;
//this loop is for sum
for(int i =0; i < arr.length; i++){
lsum += arr[i];
}
//this loop is for calculating sum from reverse
for(int j= arr.length - 1; j >= 0; j--){
lsum -= arr[j];
System.out.printf("%d. lsum = %d , sum = %d%n", j, lsum, sum);
if(lsum == sum){
System.out.println("Returning: " + j);
return j;
}
sum += arr[j];
}
System.out.println("Returning: -1");
return -1;
}
When I call method Calc with the sample array from your question, the following is printed:
5. lsum = 22 , sum = 0
4. lsum = 17 , sum = 6
3. lsum = 11 , sum = 11
Returning: 3
I've been looking at a for-loop that reverses the elements in an array, but I do not quite understand what's going on inside it. This is the code:
int middleIndex = (array.length) / 2;
for (int i = 0; i < middleIndex; i++) {
int temporaryVariable = array[i];
array[i] = array[array.length - 1 - i];
array[array.length - 1 - i] = temporaryVariable;
}
What exactly does the two lines below int temporaryVariable = array[i] do? How exactly does it reverse the elements?
It effectively reverses the elements of the array by swapping first with last element, second with second_last etc. In this way the number of operations are ayrray_length / 2.
The 2 lines after int temporaryVariable = array[i]; simply swap the i'th element with the i'th from last element, and we run this loop half time the number of elements in array.
First of all remember that array indexes start from 0.
So the index of the last element is the array.length - 1.
Those 3 lines are swapping the first item with the last item, then the 2nd item with the 2nd-from-last item, etc. The temporaryVariable is used as a temporary place to store one of the values during swapping, so that it doesn't get lost when it is overwritten by the other value.
Take a copy of the value at i:
int temporaryVariable = array[i];
Put item i from the end of the array (array.length - 1 - i) instead of it.
array[i] = array[array.length - 1 - i];
Put the temporarily stored item which was item i at i from the end (array.length - 1 - i).
array[array.length - 1 - i] = temporaryVariable;
The loop stops when i reaches the middle of the array. (If the array has an odd number of elements the middle one stays where it is.)
This algorithm is taking N/2 iterations of swapping values stored in an array. It starts from the beggining of the array (Index 0) and goes until its half(index N/2). It swaps the first element(indexed 0) with the last one (indexed N - 1 - 0), then swaps the second element(indexed 0 + 1) with the one before the last one(indexed N - 1 - (0 + 1)), and so on.
another part was to return the second biggest number, but for some reason it returns the third biggest number, which is really weird.
This is the code:
public static int returnSecondBiggest(int[] array) {
int largestElement = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i] > largestElement) {
largestElement = array[i];
}
}
int secondBiggest = Integer.MIN_VALUE;
for (int i = 0; i < array.length; i++) {
if (array[i] > secondBiggest && array[i] != largestElement) {
secondBiggest = array[i];
}
}
return secondBiggest;
}
How does it return the third when the code should return the second? I'm so lost.
I'm trying my hands on basic programming and I came across this question. I have a function with a return type as string, that takes an integer input and has to print the series mentioned. Here's what I did.
String s=new String("h");
int[] a=new int[n];
int k=1;
for(int i=0;i<n;i+=2)
{
a[i]=b;//line6
a[i+1]=n-(b-1);//line7
b++;
}
s=Arrays.toString(a);
return s;
When I enter an "even" no. like 4. I get the proper result [1,4,2,3].
But when I enter "odd" no. like 5. I get an ArrayOutOfBoundException
I Know where Im going wrong at line6 and line7 but I'm not getting an idea how to modify it accordingly.
I also wish to return the string as 1 n 2 n-1 3 n-2 ... instead of [1,n,2,n-1,3,n-2,..]
That's because you have a loop running from i = 0 to i < n, and you are trying to access a[i + 1]. This runs fine on even numbers because you're incrementing 2 each time, and the last iteration checks for a[n - 2] and a[n - 1].
The ArrayIndexOutOfBoundException occurs on odd numbers, however, because the last iteration attempts to access a[n - 1] and a[n].
One way to modify the loop would be to increment only by 1, and set the value of a[i] by checking the parity of i inside the loop:
for(int i = 0; i < n; i++, b++) {
a[i] = (i % 2 == 0)? b: (n - (b - 1));
}
consider the next approach:
for(int i=0;i<n/2;i++)
{
a[2*i] = i+1;
a[2*i+1] = n-i;
}
if (n&1==1) //how to check for oddity in Java?
a[n-1] = (n+1)/2
The inside of your loop should look like
a[i] = b;
if (i + 1 < n) { // check the bounds before writing at i+1
a[i + 1] = n - (b - 1);
}
b++;
The reason for that is that when having odd numbers (e.g. 5) i gets to become 4 in the last iteration of the loop, 4 is smaller than 5, therefore the code enters the loop, then you access a at index 4, which is okay, but then you try to access it at 4+1, which is 5, but the array does not have an index 5 because.
Split the problem up into two smaller problems:
Generating all values for even indices
for(int i = 0; i < a.length; i += 2)
a[i] = i + 1;
Generating all values for odd incides
for(int i = 1; i < a.length; i += 2)
a[i] = n - i / 2;
Thanks to integer-division i / 2 of an odd number can substitute (i - 1) / 2.
Full code
int[] a = new int[n];
for(int i = 0; i < a.length; i += 2)
a[i] = i + 1;
for(int i = 1; i < a.length; i += 2)
a[i] = n - i / 2;
return Arrays.toString(a);
I have an ArrayList which contain 10 elements and a variable int = 12. Now I want to count how many elements are in array and if are less than 12 to start to count again from 0 and stop to index 2 and remove it, until I will have one element in my array. I tried the following:
int j = 12;
int l = 0;
// Here I check if j is less than array.size
while (j < array.size()) {
for (int i = 0; i < array.size(); i++) {
if (j == i + 1) {
array.remove(i);
}
}
}
// Here is for j greater than array.size
while (array.size() != 1) {
for (int i = 0; i < array.size(); i++) {
l = j - array.size();
if (l < array.size()) {
array.remove(l);
}
}
}
System.out.println(array);
UPDATE:
MyArray = {1,2,3,4,5,6,7,8,9,10};
int=12;
MyArray contain just 10 elements, but I want to delete the index with number 12, as long as index 12 does not exist I should start to count again from zero, and the number 12 is at index 2, That's why I should delete the index with number 2. The second iteration MyArray will contain just 9 elements, and again 12-9=3, I should delete the index with number 3, until I will have just one element in MyArray
Instead of looping twice through the array to remove the last n elements until the length of the list equals j, you could simply use:
while (j < array.size()) {
array.remove(j - 1);
}
If you always want to remove index 2, you could do:
while (array.size() >= 3) { // otherwise you will get a ArrayIndexOutOfBoundsException
array.remove(2);
}
However, you will have two elements left in your ArrayList instead of 1 (at index 0 and 1). You cannot delete ìndex 2 at that point, because it is not a valid index any longer.
Thus, you could either remove index 0/1 afterwards or what I think you want to achieve:
while (array.size() >= 2) { // otherwise you will get a ArrayIndexOutOfBoundsException
array.remove(1);
}
Then only one element will remain in your list at index 0.
Edit: for the update of your question it is
int originalSize = array.size();
while (array.size() >= originalSize - j) { // otherwise you will get a ArrayIndexOutOfBoundsException
array.remove(originalSize - j);
}
However, you will always be left with size - j items in your list. You cannot remove index 3, for example, until you have only one element in your list.
An answer to the updated question:
When you have a list of length 10 and you want to delete the "12th element" you can use the modulo operator:
ArrayList<...> someList = ...;
int toDelete = 12;
int deleteInRange = toDelete % someList.size();
someList.remove(deleteInRange);
The modulo operator will deliver the rest of the integerdivision 12 / 10 (toDelete % someList.size())
You can use this code snippet in a loop in order to remove multiple elements.
If you always want to remove index 2, you could do:
l = j - array.size();
Change this line as below:
int sum = 0;
sum = l - array.size();
if (sum > 0) {
array.remove(sum);
} else {
sum = array.size() - l;
array.remove(sum);
}
Hello I am trying to reverse an ArrayList without the reverse method. I just wanted to make it work without the method. I can't seem to get it right.
This is what i have so far:
for (int x = nums.size()-1; x>=0; x--)
{
for(int z =0; z<nums.size();z++)
{
nums.set(z, x);
}
}
This is my output:
run:
0
1
2
3
1
1
1
1
BUILD SUCCESSFUL (total time: 0 seconds)
You can ascend from the bottom & simultaneously descend from the top (size() - 1) swapping elements, and stop when you meet in the middle.
int i = 0;
int j = nums.size()-1;
while (i < j) {
int temp = nums.get(i);
nums.set( i, nums.get(j));
nums.set( j, temp);
i++; j--;
}
You can swap in pairs at a time, coming in from both ends toward the center:
for (int i = 0; i < nums.size()/2; i++) {
Integer left = nums.get(i);
Integer right = nums.get(nums.size()-1-i);
nums.set(i, right);
nums.set(nums.size()-1-i, left);
}
By using Integer instead of int for left and right, Java doesn't have to keep converting between int and Integer values (the first being a primitive, the second being an actual object). This improves performance.