0
public class first {
    public static void main(String args[]){
        int arr[]={5,4,1,3,2};

        for(int i=0; i<arr.length-1;i++){
            int smallest=arr[i];                     
            for(int j=i+1; j<arr.length;j++){
                if(smallest>arr[j]){
                    smallest=arr[j];
                }
            }
            //swap
            int temp=smallest;
            smallest=arr[i];
            arr[i]=temp;
        }
        
        for(int i=0;i<arr.length;i++){
            System.out.print(arr[i]+" ");
        }
    }
}

i have done this problem by getting the smallest in terms of index number and the program works properly . but when i am taking smallest in terms of number present at index number , this program did not work.your text

1
  • well you need 2 indexes to do the sort the i index and the lowest number index and then you need to replace their positions with each other Commented Jan 7, 2023 at 8:13

1 Answer 1

0

you need to save the smallest number index not the number it self so you know the positions to make the swap

    for (int i = 0; i < arr.length - 1; i++) {
        int indexOfSmallestNum = i;
        for (int j = i + 1; j < arr.length; j++) {
            if (arr[indexOfSmallestNum] > arr[j]) indexOfSmallestNum = j;
        }
        int temp = arr[i];
        arr[i] = arr[indexOfSmallestNum];
        arr[indexOfSmallestNum] = temp;
    }
Sign up to request clarification or add additional context in comments.

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.