Selection sort in java with two arrays

 

selection sort in java


Selection sort in java with two values (arrays)

Selection sort
In the following program, we have done a selection sort on two arrays, age, and name. Here selection sorting is done by name in ascending order.

public class SelectionSortWithTwoValue

{

    public static void main(String args[])

    {

        int age[]={15,17,20,18,14};  // age array

        String name[]={"Habib","Junaid","Vikash", "Anthony", "Dhoni"}; // name array

        int i, j, temp1;

        String temp2;   // temporary variable for name for swaping data

        System.out.println("Name\t\tAge");

        System.out.println("=====================");

        for(i=0;i<5;i++)

        {

             System.out.println(name[i] + "\t\t" + age[i]);

        }

// selection sort is started

        for(i=0;i<4;i++)

        {

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

            {

                if(name[i].compareTo(name[j])>0)

                {

                    temp2=name[i];

                    name[i]=name[j];

                    name[j]=temp2;

                    temp1=age[i];

                    age[i]=age[j];

                    age[j]=temp1;

                }

            }

        }

// selection sort is ended

        System.out.println("Name\t\tAge");

        System.out.println("=====================");

        for(i=0;i<5;i++)

        {

             System.out.println(name[i] + "\t\t" + age[i]);

        }

    }

}

Output

Before sorting
Name Age
=====================
Habib 15
Junaid 17
Vikash 20
Anthony 18
Dhoni 14

After sorting
Name Age
=====================
Anthony 18
Dhoni 14
Habib 15
Junaid 17
Vikash 20


SHARE THIS
Previous Post
Next Post