0

I have this code and I do not know why the selection sort is not sorting all the way Does anyone know where to fix the program. The selection sort code I believe is right i just dont know what is wrong. The code is functioning

import java.util.Scanner;

public class selectionSort
{
   public static void main(String[] args)
{
  Scanner scanner = new Scanner(System.in);

  int temp;

  int i,j,first;



  System.out.println("How many numbers do you want to enter?");
  int ammount = scanner.nextInt();
  int[]array = new int[ammount];

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

     System.out.println("Enter the numbers now.");
     array[i] = scanner.nextInt();

  }

  System.out.println("\nThe  array is:");
  for(i = 0; i < array.length; i++){
     System.out.print(array[i] + " ");

  }




  for (i=array.length - 1; i>0;i--)
  {
     first=0;
     for(j=1;j<=1;j++)
     {
        if(array[j]<array[first])
           first = j;

     }

     temp = array[first];

     array[first] = array[i];
     array[i]=temp;

  }


  System.out.println("\nThe sorted array is:");
  for( i = 0; i < array.length; i++){
     System.out.print(array[i] + " ");

   }

 }

}

1 Answer 1

4

You appear to have a typo. This line:

for(j=1;j<=1;j++)

should probably be:

for(j=1;j<=i;j++)

(The loop termination test should be j<=i, not j<=1.)

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.