# Thread: Help with a sorting algorithm

1. Member Join Date
Mar 2008
Posts
17
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);
}
}
}
}  Reply With Quote

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?

Goldest  Reply With Quote

3. Member Join Date
Mar 2008
Posts
17
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);

}
}
}  Reply With Quote

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•