i created a class in which i created a method for selection sort. I took the array as user input and passed in selection sort. before calling, it displayed the values. After calling all the elements were 0.
import java.util.Scanner;
public class Selectionsortarray {
public static void Selectionsort(int num[]) {
for (int i=0;i<num.length;i++) {
for (int j=i+1;j<num.length;j++) {
if (num[j]<num[i]) {
int temp=num[i];
num[i]=num[j];
num[j]=temp;
}
}
}
}
public static void main(String[] args) {
Scanner k = new Scanner(System.in);
int a[] = new int[40];
System.out.println("Enter the no. of elements");
int n= k.nextInt();
System.out.println("Enter the array");
for (int i=0;i<n;i++) {
a[i] = k.nextInt();
}
System.out.println("The array before sorting is");
for (int i=0;i<n;i++) {
System.out.println(a[i]);
}
Selectionsort(a);
System.out.println("The array is");
for (int i=0;i<n;i++) {
System.out.println(a[i]);
}
k.close();
}
}
Your program should work perfectly fine. The issue here is, you defined array of 40 elements which gets initialized by default with 0, post that you overwrite the numbers that user enters and at the end post sorting you are just printing n elements in ascending order which will print all zero's.
You need to remove this line:
And paste it below
int n = k.nextInt();
likeAnd it should work.
This will save space and make your sorting faster as you will end up doing less iteration.