not displaying sorted array

64 Views Asked by At

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();

    }
}
3

There are 3 best solutions below

0
On BEST ANSWER

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:

int a[] = new int[40];

And paste it below int n = k.nextInt(); like

int a[] = new int[n];

And it should work.

This will save space and make your sorting faster as you will end up doing less iteration.

0
On

You are creating an array with 40 elements, and sorting it, instead of creating an array of size n (the user provided input).

This results in the array having n elements at the beginning that are provided by you, and the tail is all zeros (40-n elements). When you sort the array - these zeros are pushed to the beginning, and when you print - you print only them.

Easiest way to fix it is to change the line:

int a[] = new int[40];

into

int a[] = new int[n];

and push it AFTER you scan the length of the array.


Also note, that if you try to insert more than 40 elements to your array (n>40) in the current code, it will crash.

0
On

The a array has 40 positions, the numbers greater than 0 are at the end of the array and you are only showing the firts n elements of the ordered array wich are 0 all of them.