Results 1 to 3 of 3
Thread: Help with a sorting algorithm
- 01-14-2011, 09:59 AM #1
Member
- Join Date
- Mar 2008
- Posts
- 13
- Rep Power
- 0
Help with a sorting algorithm
This algorithm is supposed to put an array in descending order but at some point the variable lo is reassigned to the number 2 and I have no idea why!!
public class Test{
static int data[] = {37, 11, 52, 7};
static int lo = 0;
static int hi = 3;
public static void main (String args[]){
proc(data, lo, hi);
}
public static void proc(int[] data, int lo, int hi){
if (lo < hi){
if (data [lo] < data[lo + 1]){
int t = data[lo + 1];
data[lo + 1] = data[lo];
data[lo] = t;
}
proc (data, lo + 1, hi);
if (lo == 0){
proc (data, 0, hi-1);
}
}
}
}
- 01-14-2011, 10:15 AM #2
I just ran your code and it just work correctly. I iterated over the array to see the descending order of integers, and everything looked fine.
Even the variables lo and hi are printed with their default values, 0 and 3.
What is your problem in this program?
GoldestJava Is A Funny Language... Really!.gif)
Click on * and add to member reputation, if you find their advices/solutions effective.
- 01-14-2011, 12:39 PM #3
Member
- Join Date
- Mar 2008
- Posts
- 13
- Rep Power
- 0
Still not understanding
I am running this code with a debugger to check how the variables are changing and at one point in time the variable lo changes from 3 to 2 by first going to the last curly bracket of the method and jumps to the if(lo==0) statement. I cannot understand this when there is in no part lo= lo-1; or something similar. I highlighted the parts where it jumps from one statement to another
public class Test{
public static void main (String args[]){
int data[] = {37, 11, 52, 7};
int lo = 0;
int hi = 3;
proc(data, lo, hi);
}
public static void proc(int[] data, int lo, int hi){
if (lo < hi){
if (data [lo] < data[lo + 1]){
int t = data[lo + 1];
data[lo + 1] = data[lo];
data[lo] = t;
}
proc (data, lo + 1, hi);
if (lo == 0)
proc (data, 0, hi-1);
}
}
}
Similar Threads
-
Algorithm help? :)
By Mirix in forum New To JavaReplies: 6Last Post: 05-24-2010, 02:08 AM -
Need some help in an algorithm
By ea09530 in forum New To JavaReplies: 3Last Post: 04-04-2010, 01:13 PM -
Help with an Algorithm
By Manfizy in forum New To JavaReplies: 22Last Post: 07-03-2009, 07:16 AM -
O(log n) algorithm help !!!!!!
By itseeker87 in forum New To JavaReplies: 8Last Post: 09-09-2008, 05:12 PM -
Help with algorithm
By susan in forum New To JavaReplies: 1Last Post: 07-13-2007, 10:26 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks