Java Example – Selection Sort Algorithm




Java Tutorial for Beginners
Java Tutorial for Beginners

Selection Sort Algorithm using Java

Selection Sort

    • Repeatedly searches for the largest value in a section of the data
      • Moves that value into its correct position in a sorted section of the list
    • Uses the Find Largest algorithm

 Pseudo Code

 

  • Count comparisons of largest so far against other values
  • Find Largest, given m values, does m-1 comparisons
  • Selection sort calls Find Largest n times,
    • Each time with a smaller list of values
    • Cost = n-1 + (n-2) + … + 2 + 1 = n(n-1)/2

 Efficiency

  • Time efficiency
    • Comparisons: n(n-1)/2
    • Exchanges: n (swapping largest into place)
    • Overall: (n2), best and worst cases
  • Space efficiency
    • Space for the input sequence, plus a constant number of local variables

 

In this lesson we will learn how to write a source code in Java programming language for doing simple Selection sort using array in ascending order.

Java Example :

import java.util.Arrays;

/**
 * Created by ProgrammingKnowledge.
 */
public class SelectionSort {

    public static int[] doSelectionSort(int[] arr){

        for (int i = 0; i < arr.length - 1; i++)
        {
            int index = i;
            for (int j = i + 1; j < arr.length; j++)
                if (arr[j] < arr[index])
                    index = j;

            int smallerNumber = arr[index];
            arr[index] = arr[i];
            arr[i] = smallerNumber;
        }
        return arr;
    }



    public static void main(String a[]){

        int[] list = {4,3,2,5,9,6,3,21,42,4,3,6};
        System.out.println("Before Selection sort\n");
        System.out.println(Arrays.toString(list));
        list = doSelectionSort(list);
        System.out.println("\nAfter Selection sort");
        System.out.println(Arrays.toString(list));

    }
}

/**
 * Output
 Before Selection sort

 [4, 3, 2, 5, 9, 6, 3, 21, 42, 4, 3, 6]

 After Selection sort
 [2, 3, 3, 3, 4, 4, 5, 6, 6, 9, 21, 42]
 */

 
 





Partner Sites

VideoToGifs.com

EasyOnlineConverter.com

SqliteTutorials.com





Be the first to comment

Leave a Reply

Your email address will not be published.


*