0

I have learnt selection sort, and i try to code it with java. But it has an error, i think it a runtime error. I don't know what to fix in my code.

This is the code:

import java.util.Scanner;

public class Main {

    public static void main(String args[])
    {

        int temp;

        Scanner sc=new Scanner(System.in);
        int number;
        int input=sc.nextInt();
        int [] carriage;
        carriage=new int[input];
        for(int i=0;i<input;i++)
        {
            number=sc.nextInt();
            carriage[i]=number;


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

            }
            System.out.println(carriage[i]+ " ");
        }
        sc.close();
    }
}
3
  • 2
    i think it a runtime error. I don't know what to fix. You can start by adding the error to your answer. Also it might be worthwhile to take a look at how to ask Commented Oct 9, 2019 at 16:16
  • 1
    for(int j=i+1;i<n;j++) are you sure this is correct? I think it should be for(int j=i+1;j<n;j++) Commented Oct 9, 2019 at 16:26
  • @CocoNess yeah man thanks alot hahaahaha Commented Oct 9, 2019 at 16:27

1 Answer 1

1

I think you want to sort the number of integer provided by user. Your code is having 2 errors. One in the for loop starting with i, the condition should be i

public class Main {

    public static void main(String args[]) {

        int temp;

        Scanner sc = new Scanner(System.in);
        int number;
        System.out.println("Enter the number of integers to be sorted - ");
        int input = sc.nextInt();
        int[] carriage;
        carriage = new int[input];
        for (int i = 0; i < input; i++) {
            System.out.println("Enter the "+ i+1 +"number  - ");
            number = sc.nextInt();
            carriage[i] = number;
        }
        int n = carriage.length;
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {
                if (carriage[j] < carriage[i]) {
                    temp = carriage[i];
                    carriage[i] = carriage[j];
                    carriage[j] = temp;
                }

            }
            System.out.println(carriage[i] + " ");
        }
        sc.close();
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

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.