0

This is what I have tried, but something is wrong!

public static int[] sortIt(int[] array){
    int temp = 0;

    for(int index =0; index<array.length; index++){

    for(int i=0; i<array.length; i++){
        if(array[index]<array[i]){
            temp = array[i];
            array[0] = array[i];
            array[index] = temp;
        }
        }
    }
    return array;
}
1
  • 1
    Which language is this? Commented Sep 26, 2015 at 4:04

4 Answers 4

1

Why not just

Arrays.sort(array);

See http://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#sort(int[])

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

Comments

1

Try this:

public static int[] sortIt(int[] array) {
   int temp = 0;
   for(int index =0; index<array.length-1; index++){
      for(int i=index+1; i<array.length; i++){
          if(array[index]<array[i]){
              temp = array[index];
              array[index] = array[i];
              array[i] = temp;
          }
       }
    }
    return array;
}

Comments

0

try this

    public static void main(String[] args) {
        int[] arr = new int[]{9,5,7,1,9,4,6,3};
        insertionsort(arr);
        display(arr);
    }
    public static void insertionsort(int[] arr){
        for (int i=0; i<arr.length+0; i++)
             for (int j=i; j>0 && arr[j-1]>arr[j]; j--)
                  swap(arr, j, j-1);
    }
    private static void swap(int x[], int a, int b) {
        int t = x[a];
        x[a] = x[b];
        x[b] = t;
    }
    public static void display(int[] arr){
        System.out.print("[");
        for (int i = 0; i < arr.length; i++) {
            if (i == 0) System.out.print(arr[i]);
            else System.out.print(","+arr[i]);
        }
        System.out.println("]");
    }

Arrays.sort(arr);

Comments

0

Change 2nd loop i=0 toi=index+1 and array[0] = array[i]; to array[i] = array[index];

for(int index =0; index<array.length; index++){
    for(int i=index +1; i<array.length; i++){
        if(array[index]<array[i]){
            temp = array[i];
            array[i] = array[index];
            array[index] = temp;
        }
    }
}

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.