int[] array (sort lowest to highest)

后端 未结 11 1507
悲哀的现实
悲哀的现实 2020-12-01 13:32

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         


        
相关标签:
11条回答
  • 2020-12-01 13:58

    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+",");
        }
    
    0 讨论(0)
  • 2020-12-01 14:02

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

    0 讨论(0)
  • 2020-12-01 14:10
      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 
    
    }   
    
    }
    }
    
    0 讨论(0)
  • 2020-12-01 14:10

    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! :-)

    0 讨论(0)
  • 2020-12-01 14:10

    In java8 you can do something like this:

    temp.stream()
        .sorted((e1, e2) -> Integer.compare(e2, e1))
        .forEach(e -> System.out.println(e));  
    
    0 讨论(0)
提交回复
热议问题