9

So I am not sure why this is becoming so hard for me, but I need to sort high to low and low to high.

For high to low I have:

int a, b;
int temp;
int sortTheNumbers = len - 1;

for (a = 0; a < sortTheNumbers; ++a) {
    for (b = 0; b < sortTheNumbers; ++b) {
        if (array[b] < array[b + 1]) {
            temp = array[b];
            array[b] = array[b + 1];
            array[b + 1] = temp;
        }
    }
}

However, I can't for the life of me get it to work in reverse (low to high), I have thought the logic through and it always returns 0's for all the values. Any help appreciated!

The bigger picture is that I have a JTable with 4 columns, each column with entries of numbers, names, or dates. I need to be able to sort those back and forth.

Thanks!

3
  • Post what you have tried for low to high, and where it's running into trouble. It should only be a 1 character change (you can guess which character). Commented Mar 20, 2012 at 16:38
  • sorting apart, maybe a linked list would help you to store the values AND to trasverse them from highest to lowest and back. no need to sort them all the time. Commented Mar 20, 2012 at 16:40
  • 2
    You say you are doing that to sort a JTable: it would be easier to use a sorter rather than reimplementing a sort algorithm manually. Commented Mar 20, 2012 at 16:58

11 Answers 11

22

Unless you think using already available sort functions and autoboxing is cheating:

Integer[] arr =
    { 12, 67, 1, 34, 9, 78, 6, 31 };
    Arrays.sort(arr, new Comparator<Integer>()
    {
        @Override
        public int compare(Integer x, Integer y)
        {
            return x - y;
        }
    });

    System.out.println("low to high:" + Arrays.toString(arr));

Prints low to high:[1, 6, 9, 12, 31, 34, 67, 78]

if you need high to low change x-y to y-x in the comparator

Sign up to request clarification or add additional context in comments.

Comments

5

You are never visiting the last element of the array.

Also, you should be aware that bubble sort is pretty inefficent and you could just use Arrays.sort().

3 Comments

Why would he need to "visit" the last element of the array? There's nothing to swap it with. He does however compare it with the second-last element and swap them if they're out of order. Maybe I'm not understanding what you're suggesting, could you include a test input that doesn't work with the code he posted?
Seems Arrays.sort is an eazy one , any drawback for that one ?
Perfect answer, saved a lots of code
3
  public class sorting {
  public static void main(String arg[])throws Exception{
  int j[]={1,28,3,4,2};   //declaring array with disordered values  

  for(int s=0;s<=j.length-1;s++){
  for(int k=0;k<=j.length-2;k++){
         if(j[k]>j[k+1]){   //comparing array values

    int temp=0;    
    temp=j[k];     //storing value of array in temp variable 

j[k]=j[k+1];    //swaping values
j[k+1]=temp;    //now storing temp value in array


}    //end if block             
}  // end inner loop    
}
//end outer loop

for(int s=0;s<=j.length-1;s++){
System.out.println(j[s]);       //retrieving values of array in ascending order 

}   

}
}

Comments

3

You just need to write one string Arrays.sort(arr) for low to high for Java 8.

Arrays.sort(arr, Collections.reverseOrder()) for high to low

Comments

1

The only thing you need to do to change the sort order is change

if (array[b] < array[b + 1])

to

if (array[b] > array[b + 1])

Although, as others have noted, it's very inefficient! :-)

2 Comments

Yes I figured all I had to do was switch that sign, but it returns 0's instead of the actual values, as if it is erasing them. As for bugs, it seems unlikely since the code for the high to low is exactly the same within its own method, using the same reset variables.
Sorry, I've re-examined it and I retract the bit about bugs! It's still a super-slow bubble-sort though ;-)
1

In java8 you can do something like this:

temp.stream()
    .sorted((e1, e2) -> Integer.compare(e2, e1))
    .forEach(e -> System.out.println(e));  

Comments

0

You need a more efficient sort. like mergesort. try www.geekviewpoint.com and go to sort

Comments

0

If you just want sort the int array: Use the quicksort... It's not a lot of code and it's N*lgN in avarage or N^2 in worst-case. To sort multiple data, use the Java Compare (as above) or a stable sorting algorithm

static void quicksort(int[] a,int l, int r){
    if(r <= l) return;
    int pivot = partition(a,l,r);

    //Improvement, sort the smallest part first
    if((pivot-l) < (r-pivot)){
        quicksort(a,l,pivot-1);
        quicksort(a,pivot+1,r);
    }else{
        quicksort(a,pivot+1,r);
        quicksort(a,l,pivot-1);
    }
}

static int partition(int[] a,int l,int r){
    int i = l-1;
    int j = r;
    int v = a[r];
    while(true){
        while(less(a[++i],v));  //-> until bigger
        while((less(v,a[--j]) && (j != i)));    //-> until smaller and not end
        if(i >= j){
            break;
        }
        exch(a,i,j);
    }
    exch(a,i,r);
    return i;
}

Comments

0

If you want to apply same logic as what you have done...by not using Arrays.sort...then following will help

int[] intArr = {5, 4, 3, 8, 9, 11, 3, 2, 9, 8, 7, 1, 22, 15, 67, 4, 17, 54};
    //Low to high
    for(int j=0; j<intArr.length-1; j++){
        for(int i=0; i<intArr.length-1; i++){
            if (intArr[i] > intArr[i+1]){
                int temp = intArr[i+1];
                intArr[i+1] = intArr[i];
                intArr[i] = temp;
            }
        }
    }
    //High to low
    for(int j=0; j<intArr.length-1; j++){
        for(int i=0; i<intArr.length-1; i++){
            if (intArr[i] < intArr[i+1]){
                int temp = intArr[i+1];
                intArr[i+1] = intArr[i];
                intArr[i] = temp;
            }
        }
    }
    for(int ars : intArr){
        System.out.print(ars+",");
    }

Comments

-2

Let me know if this works:

public class prog1 {
    public static void main (String args[]){
        int a[] = {1,22,5,16,7,9,12,16,18,30};

        for(int b=0; b<=a.length;b++){
            for(int c=0; c<=a.length-2;c++){
                if(a[c]>a[c+1]){

                    int temp=0;
                    temp=a[c];

                    a[c]=a[c+1];
                    a[c+1]=temp;
                }
            }

        }
        for(int b=0;b<a.length;b++){
            System.out.println(a[b]);
        }
    }
}

2 Comments

Did you not try it to see if it worked before posting it? Even if you are on a mobile device (say), you can still use sites like ideone.com where you can write code and run it, e.g. your answer is this.
In that case, you'd maybe be best off rewording your answer to be more of a statement (e.g. "this method works", etc.) If you explain why you've done what you did you'd stand a better chance of getting upvoted. (Also fix the formatting - consistent indentation, etc.).
-3

You can try with bubble sort: Example shown below

int[] numbers = { 4, 7, 20, 2, 56 };
int temp;

for (int i = 0; i < numbers.length; i++)
{
       for(int j = 0; j < numbers.length; j++)
       {
                if(numbers[i] > numbers[j + 1])
                {
                            temp = numbers [j + 1];
                            numbers [j + 1]= numbers [i];
                            numbers [i] = temp;
                }
        }
}

for (int i = 0; i < numbers.length; i++)
{
         System.out.println(numbers[i].toString());
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.