**This Tutorial will Explain all about Selection Sort In Java along with Selection Sort Algorithm, Java Code, Implementation in Java and Java Examples:**

The selection sort technique is a method in which the smallest element in the array is selected and swapped with the first element of the array. Next, the second smallest element in the array is exchanged with the second element and vice versa.

**=> Check Here To See A-Z Of Java Training Tutorials Here.**

What You Will Learn:

## Selection Sort In Java

This way the smallest element in the array is selected repeatedly and put in its proper position until the entire array is sorted.

**Two sub-arrays are maintained for selection sort:**

**Sorted sub-array:**In every iteration, the minimum element is found and placed in its proper position. This sub-array is sorted.**Unsorted sub-array:**The remaining elements that are not sorted.

The selection sort is a straightforward and easy sorting technique. The technique only involves finding the smallest element in every pass and placing it in the correct position. The selection sort is ideal for smaller data sets as it sorts the smaller dataset efficiently.

Thus we can say selection sort is not advisable for larger lists of data.

### Selection Sort Algorithm

**The General Algorithm for Selection Sort is given below:**

**Selection Sort (A, N)**

**Step 1**: Repeat Steps 2 and 3 for K = 1 to N-1

**Step 2**: Call routine smallest(A, K, N, POS)

**Step 3**:

Swap A[K] with A [POS]

[End of loop]

**Step 4**: EXIT

**Routine smallest (A, K, N, POS)**

**Step 1**: [initialize] set smallestItem = A[K]

**Step 2**: [initialize] set POS = K

**Step 3**:

for J = K+1 to N -1, repeat

if smallestItem > A [J]

set smallestItem = A [J]

set POS = J

[if end]

[End of loop]

**Step 4**: return POS

As you can see, the routine to find the smallest number is called while traversing the data set. Once the smallest element is found, it is placed in its desired position.

### Pseudocode For Selection Sort

**The pseudo-code for the selection sort algorithm is given below.**

Procedure selection_sort(array,N) array – array of items to be sorted N – size of array begin for I = 1 to N-1 begin set min = i for j = i+1 to N begin if array[j] < array[min] then min = j; end if end for //swap the minimum element with current element if minelem != I then swap array[min[] and array[i] end if end for end procedure

Let us now illustrate the sorting of an array using selection sort.

### Selection Sort Example

**Consider the following array that is to be sorted as an example of a selection sort.**

**Given below is a tabular representation for the illustration:**

Unsorted list | Least element | Sorted list |
---|---|---|

{17,10,7,29,2} | 2 | {} |

{17,10,7,29} | 7 | {2} |

{17,10,29} | 10 | {2,7} |

{17,29} | 17 | {2,7,10) |

{29} | 29 | {2,7,10,17} |

{} | {2,7,10,17,29} |

From the illustration, we see that with every pass the next smallest element is put in its correct position in the sorted array. In general, to sort an array of N elements, we need N-1 passes in total.

### Selection Sort Implementation In Java

**Let’s now demonstrate the Java program to implement selection sort.**

import java.util.*; class Main { static void sel_sort(int numArray[]) { int n = numArray.length; // traverse unsorted array for (int i = 0; i < n-1; i++) { // Find the minimum element in unsorted array int min_idx = i; for (int j = i+1; j < n; j++) if (numArray[j] < numArray[min_idx]) min_idx = j; // swap minimum element with compared element int temp = numArray[min_idx]; numArray[min_idx] = numArray[i]; numArray[i] = temp; } } public static void main(String args[]) { //declare and print the original array int numArray[] = {7,5,2,20,42,15,23,34,10}; System.out.println("Original Array:" + Arrays.toString(numArray)); //call selection sort routine sel_sort(numArray); //print the sorted array System.out.println("Sorted Array:" + Arrays.toString(numArray)); } }

**Output:**

Original Array:[7, 5, 2, 20, 42, 15, 23, 34, 10]

Sorted Array:[2, 5, 7, 10, 15, 20, 23, 34, 42]

In the above java example, we repeatedly find the smallest element in the array and put it in the sorted array until the entire array is completely sorted.

### Selection Sort Linked List In Java

Given below is a linked list and we have to sort it using selection sort. To do this we will use the recursive approach of selection sort. Instead of swapping the data part of the node, we will swap the nodes and realign the pointers.

**So if the linked list is given as follows:**

**Given below is the Java program that implements the above sorting.**

// add a node to the beginning of the linked list static Node addNode( Node head_ref, int new_data) { // create a node Node newNode = new Node(); // assign data to node newNode.data = new_data; // link the node to linked list newNode.next = (head_ref); //head now points to new node (head_ref) = newNode; return head_ref; } // method to swap nodes static Node swapNodes( Node head_ref, Node curr_node1, Node curr_node2, Node prev_node) { // curr_node2 is new head head_ref = curr_node2; // realign links prev_node.next = curr_node1; // now swap next pointers of nodes Node temp = curr_node2.next; curr_node2.next = curr_node1.next; curr_node1.next = temp; return head_ref; } // sort the linked list using selection sort static Node Selection_Sort( Node head) { // only a single node in linked list if (head.next == null) return head; // minNode => node with minimum data value Node minNode = head; // prevMin => node previous to minNode Node prevMin = null; Node ptr; // traverse the list from head to last node for (ptr = head; ptr.next != null; ptr = ptr.next) { // check if current node is minimum if (ptr.next.data < minNode.data) { minNode = ptr.next; prevMin = ptr; } } // minimum node becomes head now if (minNode != head) head = swapNodes(head, head, minNode, prevMin); // sort remaning list recursively head.next = Selection_Sort(head.next); return head; } // sort the given linked list static Node sort( Node head_ref) { // linked list is empty if ((head_ref) == null) return null; // call Selection_Sort method to sort the linked list head_ref = Selection_Sort(head_ref); return head_ref; } // print nodes of linked list static void printList( Node head) { while (head != null) { System.out.print( head.data + " "); head = head.next; } } public static void main(String args[]) { Node oddList = null; // create linked list using addNode method oddList = addNode(oddList, 11); oddList = addNode(oddList, 1); oddList = addNode(oddList, 5); oddList = addNode(oddList, 3); oddList = addNode(oddList, 9); oddList = addNode(oddList, 7); //print the original list System.out.println( "Original Linked list:"); printList(oddList); // sort the linked list oddList = sort(oddList); //print the sorted list System.out.println( "\nLinked list after sorting:"); printList(oddList); } }

**Output:**

Original Linked list:

7 9 3 5 1 11

Linked list after sorting:

1 3 5 7 9 11

Note that in the above program, we have realigned links of the nodes instead of sorting only the data component of the node.

### Frequently Asked Questions

**Q #1) How does Selection sort work?**

**Answer:** Selection sort works by maintaining two sub-arrays. The minimum element from the unsorted subarray is placed in its proper position in a sorted sub-array. Then the second-lowest element is placed in its proper position. This way, the entire array is sorted by selecting a minimum element during each iteration.

**Q #2) ****What is the complexity of the Selection sort?**

**Answer:** The overall complexity of selection sort is O (n^{2}), thereby making it the algorithm that is inefficient on larger data sets. Other sorting techniques are more efficient.

**Q #3) ****What are the Advantages and Disadvantages of Selection sort?**

**Answer:** Selection sort is the in-place sorting technique and thus it does not require additional storage to store intermediate elements.

It works efficiently on smaller data structures as well as the data sets that are almost sorted.

The major disadvantage of the selection sort technique is that it performs very poorly as the size of the data structure increases. It not only becomes slower but also decreases efficiency.

**Q #4) ****How many swaps are there in the Selection sort?**

**Answer:** The selection sort technique takes the minimum number of swaps. For the best case, when the array is sorted, the number of swaps in the selection sort is 0.

**Q #5) ****Is selection sort faster than Insertion sort?**

**Answer:** Insertion sort is faster and more efficient as well as stable. Selection sort is faster only for smaller data sets and partially sorted structures.

## Conclusion

Selection sort is a technique that works by selecting the minimum element while traversing the array. For each pass/iteration, the next minimum element in the data set is selected and placed in its proper position.

The selection sort technique works efficiently when the number of elements in the data set is smaller, but it starts to perform poorly as the size of the data set grows. It becomes inefficient when compared to the other similar techniques like insertion sort.

**In this tutorial, we have implemented examples to sort arrays and linked lists using selection sort. **

**=> Visit Here To See The Java Training Series For All.**