# Selection Sort Pseudocode and Flowchart in Java with Example

[24840 views]

### What is Selection Sort?

Selection Sort is one of the most simple sorting algorithm that sorts the data items into either ascending or descending order, which comes under the category of in-place comparison sort algorithm. Sorting in Selection Sort Algorithm takes place by stepping through all the data items one-by-one while looking for either the largest or the smallest data item and making only one swap after finding either largest or smallest data item. Hence, this sorting algorithm is referred to as the selection sort because on each pass this algorithm selects either largest or smallest of the remaining unsorted data items and places the selected data item in the right order.

### Pseudocode for Selection Sort Algorithm:

1. Find the smallest element in the given array. 2. Exchange that smallest element found with the element at the first position. 3. Then find the second smallest element in the array and exchange that element with the element at the second position. 4. Repeat finding the next-smallest element, and exchange it with element in the correct position until the complete array is sorted.

### Flowchart for Selection Sort Algorithm: ### Java Program for Selection Sort Algorithm:

public class SelectionSort { public static void main(String a[]) { int[] arr = {260,8,800,56}; System.out.println("------Before Selection Sort-----"); printArray(arr); selection(arr);//sorting array using selection sort algorithm System.out.println("-----After Selection Sort-----"); printArray(arr); } public static void selection(int[] array) { for (int i = 0; i < array.length - 1; i++) { System.out.println("Sort Pass Number "+(i+1)); int index = i; for (int j = i + 1; j < array.length; j++) { System.out.println("Comparing "+ array[index] + " and " + array[j]); if (array[j] < array[index]){ System.out.println(array[index] + " is greater than " + array[j] ); index = j; } } int smallerNumber = array[index]; array[index] = array[i]; array[i] = smallerNumber; System.out.println("Swapping Elements: New Array After Swap"); printArray(array); } } static void printArray(int[] array){ for(int i=0; i < array.length; i++) { System.out.print(array[i] + " "); } System.out.println(); } }

### Output

C:\Users\SK\Desktop\javaPrograms>javac SelectionSort.java C:\Users\SK\Desktop\javaPrograms>java SelectionSort ------Before Selection Sort----- 260 8 800 56 Sort Pass Number 1 Comparing 260 and 8 260 is greater than 8 Comparing 8 and 800 Comparing 8 and 56 Swapping Elements: New Array After Swap 8 260 800 56 Sort Pass Number 2 Comparing 260 and 800 Comparing 260 and 56 260 is greater than 56 Swapping Elements: New Array After Swap 8 56 800 260 Sort Pass Number 3 Comparing 800 and 260 800 is greater than 260 Swapping Elements: New Array After Swap 8 56 260 800 -----After Selection Sort----- 8 56 260 800