views:

41

answers:

0

Possible Duplicate:
Java backtracking problem

This problem must be used by backtracking method. I want to sort an input such as "4 2 5 1" which will convert into an array to become " 1 2 4 5" some codes are like below, i tried to build the logic, but it failed to work.

public static Node<Integer> sort_it(int[] arr, int fst, int last, Node<Integer> part_soln)
{
    //System.out.println("sort_bt with "+fst+" "+last); // for debugging
    if (fst>last) {
        return part_soln; // return a sorted list
    } else { 
          for (int row=0; row<last; row++)
          {
              if (sorted_test(arr[row],part_soln))
              { Node<Integer> new_soln = new Node<Integer>(row,part_soln);
                Node<Integer> ret=sort_it(arr,fst++,last,new_soln);
               if(ret!=null) return ret;
              }
          }
          return null; 
        }
}

private static boolean sorted_test(int x, Node<Integer> soln)
{
    if (soln==null) return true;
    else if (x<=soln.getItem()) return true;
    else return false;
}

private static void swap(int[] arr, int i, int j) 
// this method swaps two locations and can be used by sort_it
{
    int tmp = arr[i];
    arr[i] = arr[j];
    arr[j]=tmp;
 }

please help me, i tried hard to understand the backtrack logic, but look the the logic i understood is not correct