Search code examples
javasortingintegerselection-sort

Need help in understanding this specific descending order selectiion sort of integers


As said in title, this is a descending sort of integer using selecction sort.This is the program.. I m having difficulties in understanding the steps. Can someone help me in understanding it? Thanks in advance!!

import java.util.Scanner;
public class Selectionsort_descending
{
public static void main(String args[])
{
int i,j,k,m,n;
Scanner sc = new Scanner(System.in);
System.out.println("Enter any number");
n=sc.nextInt();
int a[]=new int [n];

for (i=0;i<=n-1;i++)
{
System.out.println("Enter number");
a[i]=sc.nextInt();
    }
for (j=0;j<=n-1;j++)
{
for (k=j;k<=n-1;k++)
{
if (a[j]<a[k])
{
m=a[j];
a[j]=a[k];
a[k]=m;
    }
}
    }
for (i=0;i<=n-1;i++)
{
System.out.print(a[i]+" ");
    }    
    }
}

Solution

  • First of all I would highly suggest to get your code more formatted. In Eclipse it is done by pressing [Ctrl]+[Shift]+[F].

    By doing that, your code should look like that (I did some improvements which I will explain then).

    import java.util.Scanner;
    
    public class Selectionsort_descending {
    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter any number");
        int n = sc.nextInt();
        int a[] = new int[n];
    
        for (int i = 0; i < n ; i++) {
            System.out.println("Enter number");
            a[i] = sc.nextInt();
        }
        
        for (int j = 0; j < n ; j++) {
            for (int k = j; k < n; k++) {
                if (a[j] < a[k]) {
                    int m = a[j];
                    a[j] = a[k];
                    a[k] = m;
                }
            }
        }
        
        for (int i = 0; i < n ; i++) {
            System.out.print(a[i] + " ");
        }
        
        sc.close();
    }
    }
    

    Firstly I changed the "i <= n-1" to "i < n" because I think it is much more readable like this.

    Secondly I declared all variables when they were actually used and not right at the beginning as you did.

    In the first for-loop you enter your numbers through the console.

    Then you check each number of your Array: (j for Loop)

    • go through all numbers which came after this number (k for Loop)

    • is the current number (a[j]) less than a number that is located later in the Array (a[k]) ? → Change positions

      This algorythm is also called "Selection Sort" if you want to read more about it. I hope i could help you!