Java Quicksort why / where do the values change? - java

I'm learning Java in school right now and our latest topic are sort algorithms in Java. The one that I'm trying to understand is quicksort.
To understand how that algorithm sorts numbers in an array I decided to go through my code step for step in the Eclipse debugger window.
Now there was one step that I can not comprehend even after going through it what felt like hundreds of times.
My initial array is [10, 5, 3, 22, 11, 2]
When I go through the code the program starts by swapping 10 and 2, then 5 and 3 and then 2 and 2. At that point the value for i is 1 and the value for j is -1.
Now the way I see it is that there are three conditions
while(i<=j) Which returns false, because i = 1 and j = -1
if(left < j) Which returns false, because left = 0 and j = -1
if(i < right) Which also returns false, because i = 1 and right = 1
But to my surprise when the program gets to the last bracket right before public static void display the program skips back to line 40 if(i < right)
but suddenly the values for right, i, j and pivot have changed from to 5, 2, -1, and 3 respectively.
I would be very grateful if someone could explain why the values get changed.
I have also added two pictures which show what I see on my Eclipse window step I don't understand
public class QSort {
public static void quickSort(int[] arr, int left, int right){
int i = left;
int j = right;
int temp;
int pivot = arr[(left+right)/2];
System.out.println("\n\nleft = " + left + "\tright = " + right);
System.out.println("Pivot is: " + pivot + "(" + (left+right)/2 + ")");
while(i <= j){
while(arr[i] < pivot){
System.out.println("i is: " + arr[i] + "(" + i + ")");
i++;
System.out.println("i is: " + arr[i] + "(" + i + ")");
}
while(arr[j] > pivot){
System.out.println("j is: "+ arr[j] + "(" + j + ")");
j--;
System.out.println("j is: "+ arr[j] + "(" + j + ")");
}
if(i <= j){
System.out.println("i is: " + arr[i] + "(" + i + ")");
System.out.println("j is: "+ arr[j] + "(" + j + ")");
System.out.println("Swapped " + arr[i] + "(" + i + ")"+ " with " + arr[j] + "(" + j + ")");
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
i++;
j--;
System.out.println("i is: (" + i + ")");
System.out.println("j is: (" + j + ")");
System.out.println("Pivot is: " + pivot + "(" + (left+right)/2 + ")");
}
}
if(left < j){
System.out.println("j is: (" + j + ")");
quickSort(arr, left, j);
}
if(i < right){
System.out.println("i is: (" + i + ")");
quickSort(arr, i, right);
}
}
public static void display(int[] arr){
if(arr.length > 0){
System.out.print(arr[0]);
}
for(int i = 1; i < arr.length; i++){
System.out.print(", " + arr[i]);
}
}
public static void main(String[] args) {
int[] data = new int[]{10,5,3,22,11,2};
System.out.println("Before: ");
display(data);
quickSort(data, 0, data.length-1);
System.out.println("\nAfter: ");
display(data);
}
}
Thanks a lot!

I think your problem is that you don't fully understand recursion. At least that's what it sounds like from your desription of the question.
Anyway, I've tried to simply follow your program by keeping a trace of all variables. Hope this helps:
arr left right i j pivot
----------------- ------- -------- ------- ----- ----------
[10,5,3,22,11,2] 0 5
0 5 arr[2] = 3
[2,5,3,22,11,10] 1 4
3
2
[2,3,5,22,11,10] 2 1
The while loop has finished because i<=j is now false (2 > 1).
The first condition left < j (0 < 1) is true, so you call quicksort again recursively: quicksort(arr, 0, 1) - which means you now sort the array [2,3] which is already sorted, so nothing will happen:
arr left right i j pivot
----------------- ------- -------- ------- ----- ----------
[2,3,5,22,11,10] 0 1
0 1 arr[0] = 2
0
[2,3,5,22,11,10] 1 -1
The while loop condition is now false. The first condition left < j is false as well (because 0 > -1) and the second condition i < right is also false (because 1 == 1) So this call is finished and you return to where you were. Were was that? The first condition of the table above. The state of variables and parameters is now:
arr left right i j pivot
----------------- ------- -------- ------- ----- ----------
[10,5,3,22,11,2] 0 5 2 1 3
The second condition is checked (as it is the next line executed). Its value is also true since the condition is i < right (2 < 5). So you now do quicksort again recursively: quicksort(arr, 2, 5) - which means you now sort the array [3,22,11,10]:
arr left right i j pivot
----------------- ------- -------- ------- ----- ----------
[2,3,5,22,11,10] 2 5
2 5 arr[3] = 22
3
[2,3,5,10,11,22] 4 4
5
i > j now so we exit the while loop.
The first condition left < j (2 < 4) is true, so we call quicksort(arr, 2, 4) in order to sort [5,10,11] which is already sorted. I'll skip this part as it does not change the array at all.
When the recursive call is done, we return to where we were and now the second condition will be checked. i < right (5 < 5) is false And so we're done.
The original quicksort call has finished and the array is sorted.

The first picture you have shows the debugger is inside two recursive invocations of quicksort: quicksort is called from main, and then on line 38 calls quicksort again (this is the principle of quicksort, it's a recursive strategy). So you see you're on line 40 of the inner call, then when you step from there, you go back to the previous invocation of quicksort (the debugger shows you a stack of two lines instead of three in the top left window), and you're back to the previous values of pivot, etc. The array is passed as is to all recursive invocations so it's shared, but the integer variables aren't.
I think here it's the recursion that makes it hard to understand, check your call stack.

Your efforts of studying a sorting algorithms using print statements and a debugger are commendable! But your current implementation of Quicksort is rather difficult to understand, at least initially, because it has got both iteration and recursion going on (i.e. you use loops and at the same time, you have a procedure quicksort calling itself).
Let's take a rather different approach (purely recursive approach) to see how Quicksort works and why it works. Converting this recursive procedure to an iterative one (somewhat like you have written) is, luckily, a matter of technique (in this case)! I propose we do this here because that way we might control the complexity better. Again, the reason I am doing this is to better understand what is going on.
When Sir Tony Hoare proposed the algorithm and proved its correctness, it was something like this:
public static void qsort(int[] ints, int fi, int li) {
/* the recursive procedure */
if (fi < li) {
int p = partition(ints, fi, li); // key routine -- see below
qsort(ints, fi, p - 1);
qsort(ints, p + 1, li);
}
}
That's it! Isn't beautiful? Well, it is. All you do is:
Partition the given array. In my eyes, partitioning is an elegant procedure to solve a tricky problem well. The problem is simple: Given an array of numbers, rearrange the array such that there is a number in it, all the numbers to the left of which are smaller or equal to it and all the numbers to the right of which are larger than or equal to it -- return the index of such an element in the array. I urge you to try to solve this problem on your own. Both the procedures (Lomuto and Hoare) given on Wikipedia work well.
Once you are sure that your partitioning works as expected, you recursively sort the two partitions using the same qsort procedure (the order of recursive calls does not matter) and you are done!
I tried to implement the partition procedure myself:
/**
Implements partitioning of array a from a[p] to a[r], leaves all the other elements of the array intact.
#param a the given int array
#param p int first index of the part of array to be partitioned
#param r int the second index of the part of array to be partitioned
*/
public static int partition(int[] a, int p, int r) {
//this is something I have written
int pivot = a[p];
int i = p + 1;
int j = i - 1;
while (i <= r) {
if (a[i] < pivot) {
a[j] = a[i];
a[i] = a[j+1];
j++;
}
i++;
}
a[j] = pivot;
return j;
}
private static void swap(int[] ints, int i1, int i2) {
int tmp = ints[i2];
ints[i2] = ints[i1];
ints[i1] = tmp;
}
Now, I haven't yet proved the correctness of this procedure, but we can do that separately. You can even reimplement the Lomuto procedure and see that it works to your satisfaction.
And that's it. If you now want to debug this with a debugger, you are more than equipped to do it. Here's the entire implementation.
Now, the question of converting this recursive procedure to an iterative one is very interesting and this document: (shameless plug: I wrote it) http://bit.ly/recurse-iterate should give you some clues. Actual conversion of the above Quicksort procedure to an iterative one is left as an exercise to the reader :-).

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

Intuition behind calculating the prefix and suffix sums

I am solving a LeetCode question: Minimum Number of Operations to Move All Balls to Each Box.
You have n boxes. You are given a binary string boxes of length n, where boxes[i] is '0' if the ith box is empty, and '1' if it contains one ball. In one operation, you can move one ball from a box to an adjacent box. Return an array answer of size n, where answer[i] is the minimum number of operations needed to move all the balls to the ith box. For input boxes = "001011", the output is: [11,8,5,4,3,4].
Doing it in O(n^2) is trivial. I could only solve it that way. I am trying to understand this O(n) solution, but having a hard time:
class Solution {
public int[] minOperations(String boxes) {
int n = boxes.length();
int[] left = new int[n];
int[] right = new int[n];
int[] ans = new int[n];
int count = boxes.charAt(0) - '0';
for(int i = 1 ; i < n ; i++){
left[i] = left[i - 1] + count;
count += boxes.charAt(i) - '0';
// System.out.println("i: "+i+" left[i]: "+left[i]+" left[i-1] : "+left[i-1]+" count: " + count);
}
count = boxes.charAt(n - 1) - '0';
for(int i = n - 2 ; i >=0 ; i--){
right[i] = right[i + 1] + count;
count += boxes.charAt(i) - '0';
// System.out.println("i: "+i+" right[i]: "+right[i]+" right[i+1] : "+right[i+1]+" count: " + count);
}
for(int i = 0 ; i < n ; i++) {
ans[i] = left[i] + right[i];
}
return ans;
}
}
Could someone please elaborate the logic behind:
left[i] = left[i - 1] + count;
count += boxes.charAt(i) - '0';
I understand we increment count whenever we encounter a ball, but how does left[i] = left[i - 1] + count; help us count the number of operations needed so far to move all the balls on the left to i (and vice versa in case of right)?
Thank you!
Think of left[i] as the cost to move all balls starting from 0 to ith index.
So,
left[i] =
left[i - 1] (cost to move all 1's to (i - 1) the index)
+ count (this is the total number of 1's which will all need to be moved to the ith index so, its cost is count)
This comment from #dunkypie helped:
"I finally build the intuition for the problem using DP. Here is goes. When we say calculating the number of operations for moving all the balls to the left of a box to that bax, say we are at the i th position(or box). This consists of two parts, first dp[i - 1] will give us the number of operations to move all the balls so far till (i - 1) th position and now we have all the balls till the (i - 1) th position in the (i - 1) th position(or box). Then the next part involves moving all those balls in (i - 1) th position to the i th position. Also note the cost of moving a single ball by 1 position is 1. So the recurrence relation becomes:
dp[i] = dp[i - 1] + (1 * balls) where 1 here is the cost of moving a single ball."

What's The Best Data Structure For Ignoring Or Removing Some Of Elements In DataSet In Java?

I have a set of objects and i wanna check out each of elements with previous elements.
In each time if(thisElement % previousElement == 0) I want to ignoring previousElement to prevent checking again because of time complexity.
How can i decrease size of DataSet if condition is true?
Is it better to marking and moving previousElement to first of DataSet or removing it at all?
I used ArrayList of objects but i couldn't move or remove it.I also used Iterator but it should have one loop inside another and it's complicated.How can i implement this algorithm in optimal time?
i want to move or remove previousElement in O(1).
this is my code:
public static int count_max(ArrayList<Node> nodes){
int max = Integer.MIN_VALUE;
int counter = 0;
System.err.println("nodes: "+nodes);
for(Node n : nodes){
int index = nodes.indexOf(n);
for(int i = index - 1 ; i >= 0 && nodes.get(i).mark == 0 ; i--){
counter++;
if(n.number % nodes.get(i).number == 0){
n.pred = i;
nodes.get(i).mark = 1;
n.count = nodes.get(i).count + 1;
if(n.count > max)
max = n.count;
//nodes.remove(i);
break;
}
}
}
return max;
}
the problem is find maximum count of divisible numbers given for example consider [3, 4, 6, 8 ,10, 18 ,21 ,24] are given. the answer is 3 because of [3 , 6 , 18 ] or [4 , 8 , 24] all of members should be divisible what's your solution to find this in o(nlogn) or a bit bigger.i don't want in o(n^2)
It could have been better if you had provided the logic you impemented but, based on your explanation, what I understood is, you want to remove the Previous Element if it is completely dividing Current Element from the List. If that so, below mentioned way is easy to follow
MainClass.class
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(2);
list.add(4);
list.add(8);
list.add(10);
list.add(9);
int i = 1;
System.out.println("Size of List: " + list.size());
while (i < list.size()) {
System.out.println("i : " + i);
System.out.println("Values : " + list.get(i) + ", " + list.get(i - 1));
if (list.get(i) % list.get(i - 1) == 0) {
System.out.println("Removing: " + list.get(i - 1));
list.remove(i - 1);
i = 1;
} else {
i = i + 1;
}
}
System.out.println("After removing elements(if any), size is: " + list.size());
for (int val : list) {
System.out.print(val + " ");
}
}
what this code doing is, it starts from i=1 and it keeps on checking whether (i-1)th value divides ith value or not. If (i-1)th is dividing ith value then, i is set to "1" because we need to start from beginning and maintain the condition i.e.., (i-1)th value should not divide ith value. And you can guess that, if any value is not divisible by it's previous element then, we simply increment the i till it is less than the size of the List.
Note: I assumed that you want to maintain above mentioned condition throughout the List
I hope this might help you in some way to solve your issue. And this post can be edited if anyone feels needs to be.

How exactly do arrays and for loops work together?

I understand that arrays are used to store values but when they are used with for loops I loose track of what is happening. I know that the output is 100 because I ran it in the terminal but what I need to understand is that how did it get 100 from using the for loops and the arrays because I'm not sure if it uses all three values or just the first one. Thanks in advance
Here is the problem:
public class arrays {
public static void main (String[] args) {
int[] a1 = {1, 1, 3};
mystery(a1);
}
public static void mystery(int[] a) {
for (int i = 1; i < a.length - 1; i++) {
a[i] = (a[i - 1] + a[i + 1]) /2;
}
}
}
Not entirely sure what the question you're trying to ask is but - to try and help - does it help that each time a[i] is called, it takes the value of i (also the iteration number) at each instance and uses that to find the relevant array index - which is then used for the rest of the computation.
try to add this method for tracing.
public class arrays{
public static void main(String[] args) {
int[] a1 = {1, 1, 3};
mystery(a1);
}
public static void mystery(int[] a) {
for (int i = 1; i < a.length - 1; i++) {
a[i] = (a[i - 1] + a[i + 1]) /2;
printArray(a);
}
public void printArray(int[] arr){
for(int i=0;i<arr.length;i++){
System.out.println("array[" + i + "] is now " + arr[i]);
}
}
EDIT: So what's going on back-stage?
for loop initializes i as 1.
a[1] (previously '1') is changed into (a[0] + a[2])/2 = (1 + 3)/2 = 2)
i is incremented by 1
i does not meet the condition (i < a.length - 1) because i = 2 and (a.length - 1) = (3 - 1) = 2 (2 is not less than 2, its equal to 2)
loop terminates and so is the program.
I think what you're missing is that i does not represent the index of the number 1 in your array, it is the index itself when used in the context of a[i] meaning "go to a, in index i..."
Your question is not clear. If you can provide question clearly, you will get great answers ! Anyways :
Try to think yourself.
Array position starts from "0" which is also called as the index of the array.
Here loop is going from value of
i =1 to i < the value of (array's length)-1 which is i < 2 as length of array = 3
So,
for(int i=1 ; i < a.length - 1; i++){
a[i] = (a[i - 1] + a[i + 1]) /2;
}
Now take initially value of i=1 and then run the code yourself in your mind :
1.. for i = 1,
**a[i] = (a[i - 1] + a[i + 1]) /2;**
gives a[1] = (a[0] + a[2])/2 ==> a[1] = (1+3)/2 ==> a[1] = 2
Important : you have given **i < a.length-1**
Now, a.length = 3 ok?
a.length -1 = 2 ok?
so i< a.length-1 will stop at i equals 1
So, your program will give {1,2,3} as for loop will iterate from i =1 to i=1 got it?
So only 1 value i.e. a[1] will gets changed.. a[0] and a[2] will remain same.
What happens when the method mistery(a1) is called:
1. int i is initialized to 1
2. The condition if i*a.length-1, which is (3-1), is checked; this condition is true;
3. because the condition at 2. is true, the code in the for loop is executed:
a[i] = (a[i - 1] + a[i + 1]) /2 => a[1] = (a[1-1]+a[1+1])/2 => a[1]=(a[0]+a[2])/2 =>
=> a[1]=(1+3)/2 => a[1]=2
4. after the code in the for loop is executed, i is incremented by 1, thus, the final stage of this for loop is executed: i++, i is equal to 2 right now.
5. Again, the for loop checks if the condition i<a.length-1, (3-1) is true; this time, the condition is false: i=2, 2 is not less than 2.
6. The for loop terminates its "existence", in this case the method mystery(a1) is fully executed.

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1000000 at problem2.main(problem2.java:17)

I get the following error and I don't know why. I tried looking it up, but I didn't find a solution.
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1000000 at problem2.main(problem2.java:17)
Here is my code:
//Each new term in the Fibonacci sequence is generated by adding the previous two terms.
//By starting with 1 and 2, the first 10 terms will be:
//1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
//By considering the terms in the Fibonacci sequence whose values do not exceed four million,
//find the sum of the even-valued terms.
public class problem2 {
public static void main(String[] args) {
int []a = new int[1000000];
a[0] = 1;
a[1] = 2;
int sum=0;
int i=2;
while(a[i]<=4000000){
a[i] = a[i-1] + a[i-2];
i++;
}
for(int j=0;j<i;j++){
sum = sum + a[j];
}
System.out.println("The sum is: " + sum);
System.out.println("\nThere are " + i + " numbers in the sequence.\n");
System.out.println("This are all the numbers in the sequence:");
for(int j=0;j<i;j++){
if(j+1==i){
System.out.print(a[j] + ".");
break;
}
System.out.print(a[j] + ", ");
}
}
}
The problem is not the size of the int[].
Your while loop is constantly checking if a[i] is less than 4000000 while the i variable is already one index ahead. Each loop will have a[i] == 0.
This change will fix the code for you:
int i=1;
while(a[i]<=4000000){
i++;
a[i] = a[i-1] + a[i-2];
}
This error is caused by the fact that i reaches 1000000 (the size of your array) before a[i] reaches the termination condition of your loop. Instead of testing the value of a[i] you should use a for loop like this:
for (i=2; i<a.length; i++){
a[i] = a[i-1] + a[i-2];
}
In addition, you should use the type long rather than int for the items of a because the values are getting so large that they overflow the int type and wrap around to negative values, eg:
1872856136
1063031469
-1359079691
-296048222
-1655127913
-1951176135
688663248
Edit: in fact, using an array with 1000000 elements even a long won't be big enough - if you really need values this big you would have to use BigInteger
Your array a contains 1,000,000 elements, starting from zero. When you loop through them here:
while(a[i]<=4000000)
you're exceeding the index capacity. The first index to exceed the capacity is 1,000,000, hence the error.
In your while loop, you increment i before checking if you're done. Whenever that condition gets evaluated, it gets evaluated on the element you're about to calculate - but there's nothing there yet.
This means your while loop never terminates - and eventually, i becomes 1,000,000, at which point a[i] can no longer be evaluated, causing this exception to be thrown - because the last element in a is a[999999].
You can fix this in a couple of ways; the clearest would be to start i at 1, and increment it before assigning to a[i].
As an aside, fixed-size arrays are generally a bad choice, and variable-sized lists like ArrayList<E> is a better choice - although in this particular case, that would eventually just lead to an OutOfMemoryException instead, due to the logic bug.
Add an extra condition
while(i < a.length && a[i]<=4000000)
Problem is at while loop,look into the condition
while(a[i]<=4000000)
As others have pointed out . You can do like this :
int i=2;
for(;i<a.length && a[i]<=4000000;i++)
{
a[i] = a[i-1] + a[i-2];
}
It checks that the value is less than 400000 and the index should be less than 100000.
The problem is here
while(a[i]<=4000000)
In your case you can do as
while(i < a.length && a[i]<=4000000 ){
a[i] = a[i-1] + a[i-2];
i++;
}
And your program will work perfectly..
import java.util.Scanner;
public class FibonacciSequence {
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] a = new int[40000000];
Scanner b = new Scanner(System.in);
System.out.println("Enter Two Numbers From Which You Want To Start Fibonacci Sequence.");
a[0] = b.nextInt();
a[1] = b.nextInt();
for(int i = 2; i <= 10; i++) {
a[i] = (a[i-2] + a[i-1]);
}
System.out.println("The fibonacci Sequence is: ");
int sum = 0;
for(int j = 0; j <= 10; j++) {
System.out.println(a[j] + ", ");
sum += a[j];
}
System.out.println("The Sum of the fibonacci sequence: " + sum);
}
}

Categories

Resources