I'm working on a selection sorting code to sort an array of ten integers in Java. I've written this:
import java.io.*;
class selectint
{
int array [] = new int[10];
public void sort(int arr[])
{
int i = 0;
int length = array.length;
for(i = 0; i<length ; i++)
{
int min = array[i];
int pos = i;
for(int j = i+1; j<length; j++)
{
if (min>array[j])
{
min = array[i];
pos = j;
}
}
int t = array[pos];
array[pos] = array[i];
array[i] = t;
System.out.println(array[i]);
}
}
public static void main(String args[])throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
selectint obj = new selectint();
System.out.println("Enter any 10 numbers");
String str;
int num[] = new int[10];
int i;
for( i = 0; i<10; i++)
{
str = br.readLine();
num[i] = Integer.parseInt(str);
}
obj.sort(num);
}
}
No compilation errors or syntax errors popped up. However, there was quite a logical error. I entered a set of 10 integers, but all that was printed after sorting was a set of 10 '0's. How do I resolve this? TIA.
Replace all usages of array
in the sort
method with arr
, which is the parameter you're supposed to sort.
Any IDE should tell you that arr
is unused here:
public static void sort(int arr[])
Also, you should remove the double initialization of i
:
// remove previous `i` variable declaration
for(int i = 0; i<length ; i++) { ... }