---
description: How does Selection Sort work? Selection Sort implements a simple sorting algorithm as follows: Algorithm repeatedly searches for the lowest element. Swap current element with an element having the low
title: Selection Sorting in Java Program with Example
image: https://www.guru99.com/images/selection-sorting-in-java-program.png
---

 

[Skip to content](#main) 

**⚡ Smart Summary**

Selection sort in Java repeatedly scans the unsorted part of an array, finds the smallest remaining value, and swaps it into position, completing the work with at most n-1 exchanges regardless of the input order.

* 🔘 **Definition:** Selection sort splits the array into a sorted region and an unsorted region on every pass.
* ☑️ **Process:** Each pass searches the unsorted region for the lowest element and swaps it forward.
* ✅ **Program:** The Java example sorts {860, 8, 200, 9} and prints every comparison and swap.
* 🧪 **Complexity:** Best, average, and worst cases all run in O(n²) time because the comparison count never shrinks.
* 🛠️ **Memory:** Exchanges happen inside the original array, so auxiliary space stays at O(1).
* 📊 **Behaviour:** The classic version is unstable, yet it performs the fewest writes of any quadratic sort.

[ Read More ](javascript:void%280%29;) 

![Selection Sorting in Java Program with Example](https://www.guru99.com/images/selection-sorting-in-java-program.png) 

## How does Selection Sort work?

Selection Sort implements a simple sorting algorithm as follows:

* Algorithm repeatedly searches for the lowest element.
* Swap current element with an element having the lowest value
* With every iteration/pass of selection sort, elements are swapped.

Every pass therefore treats the [array](https://www.guru99.com/java-arrays.html) as two regions: a sorted block that grows from the left and an unsorted block that shrinks on the right. The algorithm walks the unsorted block, remembers the index of the smallest value it meets, and exchanges that value with the first unsorted position.

Because only one exchange happens per pass, an array of n elements is ordered after at most n-1 swaps. That property is what separates this routine from the other beginner-level [Java](https://www.guru99.com/java-tutorial.html) sorting algorithms, which move data far more often.

The trace below follows the sample array {860, 8, 200, 9} exactly as the program in the next section prints it at run time.

| Pass  | Comparisons printed           | Smallest value found | Array after the swap |
| ----- | ----------------------------- | -------------------- | -------------------- |
| Start | —                             | —                    | 860 8 200 9          |
| 1     | 860 and 8, 8 and 200, 8 and 9 | 8                    | 8 860 200 9          |
| 2     | 860 and 200, 200 and 9        | 9                    | 8 9 200 860          |
| 3     | 200 and 860                   | 200                  | 8 9 200 860          |

Two details in that trace are worth pausing on. First, pass 3 still reports a swap even though the order does not change, because the smallest remaining value already sits at the current index and the program exchanges the element with itself. Second, the number of comparisons falls by one on each pass (three, then two, then one), which is the pattern behind the complexity figures further down the page.

## Java Program to implement Selection Sort

The class below is named SelectionSortAlgo and sits in the package com.guru99\. The main() method declares the sample array, prints it, hands it to selection() for sorting, and prints it again. The helper printArray() writes all elements on a single line, which is what produces the readable pass-by-pass log.

Inside selection(), the outer loop marks the boundary between the sorted and unsorted regions, the variable index holds the position of the smallest value seen so far, and the three assignments at the end of each pass perform the swap.

package com.guru99;
 
public class SelectionSortAlgo {
 
	public static void main(String a[])
	{  
		int[] myArray = {860,8,200,9}; 
		
		System.out.println("------Before Selection Sort-----");
 
		printArray(myArray);
 
 
		selection(myArray);//sorting array using selection sort  
 
		System.out.println("-----After Selection Sort-----");  
 
		printArray(myArray); 
	} 
	
		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:

Compiling and running the class produces the console log below, with one block of output per pass.

------Before Selection Sort-----
860 8 200 9 
Sort Pass Number 1
Comparing 860 and 8
860 is greater than 8
Comparing 8 and 200
Comparing 8 and 9
Swapping Elements: New Array After Swap
8 860 200 9 
Sort Pass Number 2
Comparing 860 and 200
860 is greater than 200
Comparing 200 and 9
200 is greater than 9
Swapping Elements: New Array After Swap
8 9 200 860 
Sort Pass Number 3
Comparing 200 and 860
Swapping Elements: New Array After Swap
8 9 200 860 
-----After Selection Sort-----
8 9 200 860

Two problems catch beginners out when they run this example for the first time. Because the file declares `package com.guru99;`, the source must live in a matching `com/guru99` directory, otherwise the compiler reports a package or class-name mismatch. The class must then be launched by its fully qualified name, `java com.guru99.SelectionSortAlgo`, because plain `java SelectionSortAlgo` raises NoClassDefFoundError.

The loop bounds are the other common trap. The outer loop stops at `array.length - 1` and the inner loop starts at `i + 1`; changing either boundary produces an extra empty pass or an ArrayIndexOutOfBoundsException.

### RELATED ARTICLES

* [Groovy Script Tutorial for Beginners ](https://www.guru99.com/groovy-tutorial.html "Groovy Script Tutorial for Beginners")
* [Java Program to Check Prime Number with Example ](https://www.guru99.com/java-program-check-prime-number.html "Java Program to Check Prime Number with Example")
* [Synchronization in Java ](https://www.guru99.com/synchronization-in-java.html "Synchronization in Java")
* [How to compare two Strings in Java ](https://www.guru99.com/compare-two-strings-in-java.html "How to compare two Strings in Java")

## Time and Space Complexity of Selection Sort

The inner loop in the program always runs to the end of the array, so the algorithm performs the same number of comparisons whatever the data looks like. For an array of n elements that total is n(n-1)/2, which for the four-element sample equals six, and the output above indeed prints exactly six Comparing lines.

| Case                        | Comparisons | Swaps | Time complexity | Auxiliary space |
| --------------------------- | ----------- | ----- | --------------- | --------------- |
| Best (array already sorted) | n(n-1)/2    | n-1   | O(n²)           | O(1)            |
| Average (random order)      | n(n-1)/2    | n-1   | O(n²)           | O(1)            |
| Worst (reverse sorted)      | n(n-1)/2    | n-1   | O(n²)           | O(1)            |

Three consequences follow from that uniform row of figures:

* Selection sort is not adaptive. Sorted input costs precisely as much as reversed input, so there is no early-exit shortcut of the kind [bubble sort](https://www.guru99.com/bubble-sort-java.html) offers.
* The swap count is the algorithm’s strong point. At most n-1 exchanges take place, which is far fewer than the quadratic number of moves other simple sorts can make.
* Memory use is constant. Only the loop counters and the two temporary variables index and smallerNumber are needed, so auxiliary space is O(1) and the sort happens in place.

The quadratic growth is the practical limit. Doubling the array size roughly quadruples the comparison work, so selection sort suits teaching, small arrays, and embedded code rather than production data sets, where O(n log n) algorithms are the correct choice.

## Advantages and Disadvantages of Selection Sort

Understanding where the algorithm helps and where it hurts makes it easier to decide when reaching for it is reasonable.

**Advantages**

* The logic is short and readable, which is why it is a standard first sorting exercise alongside [insertion sort](https://www.guru99.com/insertion-sort-java.html).
* It sorts in place, so no second array is allocated and memory use does not grow with the input.
* It performs at most n-1 writes to the array, which matters on storage where writes are slow or wear out the medium.
* Its running time is completely predictable, because the comparison count depends only on the array length.

**Disadvantages**

* Every case is O(n²), so the algorithm does not scale to large collections.
* It cannot detect an already sorted array and therefore never finishes early.
* The classic form shown above is unstable, so two equal values may end up in the opposite order.
* It compares more often than insertion sort on nearly ordered data, where insertion sort approaches linear time.

In short, choose selection sort when the array is small and each write is expensive, and avoid it whenever the data set is large or already close to sorted.

## Selection Sort vs Bubble Sort vs Insertion Sort

All three algorithms are quadratic, in-place comparison sorts, yet they behave differently once the shape of the input changes.

| Criterion                         | Selection sort         | Bubble sort                       | Insertion sort                |
| --------------------------------- | ---------------------- | --------------------------------- | ----------------------------- |
| Best-case time                    | O(n²)                  | O(n)                              | O(n)                          |
| Average and worst-case time       | O(n²)                  | O(n²)                             | O(n²)                         |
| Swaps or shifts in the worst case | n-1 swaps              | n(n-1)/2 swaps                    | Up to n(n-1)/2 shifts         |
| Stable                            | No                     | Yes                               | Yes                           |
| Adaptive to sorted input          | No                     | Yes                               | Yes                           |
| Auxiliary space                   | O(1)                   | O(1)                              | O(1)                          |
| Typical use                       | Fewest writes required | Teaching and spotting sorted data | Small or nearly sorted arrays |

The table explains a common interview answer. Selection sort wins on the number of exchanges, bubble sort wins on recognising input that is already ordered, and insertion sort is usually the fastest of the three in practice because real data is often partly sorted. None of them competes with merge sort or quicksort once the array grows past a few dozen elements.

## FAQs

⚡ Why does the outer loop stop at array.length – 1?

After n-1 passes the unsorted region holds a single element, and a lone element is already in its correct place. Running one more pass would compare nothing, so the loop bound avoids a wasted iteration.

🧠 How can AI tools help trace a selection sort pass?

AI assistants can narrate each pass in words, build extra test arrays, and count comparisons for a given input. Use the explanation as a study aid and confirm any complexity claim against a textbook before quoting it.

🤖 Can GitHub Copilot generate a selection sort method in Java?

Yes. [GitHub Copilot](https://github.com/features/copilot) completes the method from a signature or comment. Check the inner loop start and the swap lines yourself, because generated versions sometimes swap with i rather than with the stored minimum index.

🔁 Is the classic version stable, and can stability be added?

The version shown here is unstable, because a long-distance swap can jump one equal value past another. Shifting the block of elements instead of swapping preserves the original order of equal keys, at the cost of extra writes.

🔽 How do you sort in descending order instead?

Reverse the comparison inside the inner loop. Testing whether array\[j\] is greater than array\[index\] tracks the largest remaining value, so each pass moves the maximum forward and the finished array runs from high to low.

🧪 Can the algorithm be written recursively in Java?

Yes. A recursive method finds the minimum of the current subarray, swaps it into the front, then calls itself on the remainder. The comparison count is unchanged, but the call stack adds O(n) space, so the loop form is preferred.

🐞 Which coding mistakes break the implementation most often?

The frequent faults are forgetting to reset index to i at the start of each pass, starting the inner loop at i instead of i + 1, and swapping array\[j\] rather than array\[index\], which loses track of the smallest value.

📦 Does Java’s Arrays.sort() use selection sort internally?

No. Arrays.sort() applies a dual-pivot quicksort to primitives and TimSort to objects, with an insertion-style sort on tiny partitions. Selection sort appears in teaching material and hand-written code rather than in the standard library.

#### Summarize this post with:

ChatGPT Perplexity Grok Google AI 

**Stay Updated on AI** **Get Weekly AI Skills, Trends, Actionable Advice.** 

##### Sign up for the newsletter

Subscribe for Free 

You have successfully subscribed.  
Please check your inbox. 

![AI-Newsletter]() Chosen by over **350,000+** professionals 

[Scroll to top ](#wrapper)Scroll to top 

× 

Toggle Menu Close 

Search for: 

Search

```json
{"@context":"https://schema.org","@graph":[{"@type":"Organization","@id":"https://www.guru99.com/#organization","name":"Guru99","sameAs":["https://www.facebook.com/Guru99Official","https://twitter.com/guru99com"],"logo":{"@type":"ImageObject","@id":"https://www.guru99.com/#logo","url":"https://www.guru99.com/images/guru99-logo-v1-150x59.png","contentUrl":"https://www.guru99.com/images/guru99-logo-v1-150x59.png","caption":"Guru99","inLanguage":"en-US"}},{"@type":"WebSite","@id":"https://www.guru99.com/#website","url":"https://www.guru99.com","name":"Guru99","publisher":{"@id":"https://www.guru99.com/#organization"},"inLanguage":"en-US"},{"@type":"ImageObject","@id":"https://www.guru99.com/images/selection-sorting-in-java-program.png","url":"https://www.guru99.com/images/selection-sorting-in-java-program.png","width":"700","height":"250","caption":"Selection Sorting in Java Program","inLanguage":"en-US"},{"@type":"BreadcrumbList","@id":"https://www.guru99.com/selection-sorting-java.html#breadcrumb","itemListElement":[{"@type":"ListItem","position":"1","item":{"@id":"https://www.guru99.com","name":"Home"}},{"@type":"ListItem","position":"2","item":{"@id":"https://www.guru99.com/java-tutorials","name":"Java Tutorials"}},{"@type":"ListItem","position":"3","item":{"@id":"https://www.guru99.com/selection-sorting-java.html","name":"Selection Sorting in Java Program with Example"}}]},{"@type":"WebPage","@id":"https://www.guru99.com/selection-sorting-java.html#webpage","url":"https://www.guru99.com/selection-sorting-java.html","name":"Selection Sorting in Java Program with Example","dateModified":"2026-07-30T10:41:58+05:30","isPartOf":{"@id":"https://www.guru99.com/#website"},"primaryImageOfPage":{"@id":"https://www.guru99.com/images/selection-sorting-in-java-program.png"},"inLanguage":"en-US","breadcrumb":{"@id":"https://www.guru99.com/selection-sorting-java.html#breadcrumb"}},{"@type":"Person","@id":"https://www.guru99.com/author/james","name":"James Hartman","description":"I am James Hartman, a seasoned professional in Oracle Certified Java Professional tutorials, specializing in crafting comprehensive guides to help you excel in your Java certification journey.","url":"https://www.guru99.com/author/james","image":{"@type":"ImageObject","@id":"https://www.guru99.com/images/james-hartman-author-v2-120x120.png","url":"https://www.guru99.com/images/james-hartman-author-v2-120x120.png","caption":"James Hartman","inLanguage":"en-US"},"worksFor":{"@id":"https://www.guru99.com/#organization"}},{"articleSection":"Java Tutorials","headline":"Selection Sorting in Java Program with Example","description":"How does Selection Sort work? Selection Sort implements a simple sorting algorithm as follows: Algorithm repeatedly searches for the lowest element. Swap current element with an element having the low","keywords":"java","speakable":{"@type":"SpeakableSpecification","cssSelector":[".entry-title",".summary"]},"@type":"Article","author":{"@id":"https://www.guru99.com/author/james","name":"James Hartman"},"dateModified":"2026-07-30T10:41:58+05:30","image":{"@id":"https://www.guru99.com/images/selection-sorting-in-java-program.png"},"copyrightYear":"2026","name":"Selection Sorting in Java Program with Example","subjectOf":[{"@type":"FAQPage","mainEntity":[{"@type":"Question","name":"Why does the outer loop stop at array.length - 1?","acceptedAnswer":{"@type":"Answer","text":"After n-1 passes the unsorted region holds a single element, and a lone element is already in its correct place. Running one more pass would compare nothing, so the loop bound avoids a wasted iteration."}},{"@type":"Question","name":"How can AI tools help trace a selection sort pass?","acceptedAnswer":{"@type":"Answer","text":"AI assistants can narrate each pass in words, build extra test arrays, and count comparisons for a given input. Use the explanation as a study aid and confirm any complexity claim against a textbook before quoting it."}},{"@type":"Question","name":"Can GitHub Copilot generate a selection sort method in Java?","acceptedAnswer":{"@type":"Answer","text":"Yes. GitHub Copilot completes the method from a signature or comment. Check the inner loop start and the swap lines yourself, because generated versions sometimes swap with i rather than with the stored minimum index."}},{"@type":"Question","name":"Is the classic version stable, and can stability be added?","acceptedAnswer":{"@type":"Answer","text":"The version shown here is unstable, because a long-distance swap can jump one equal value past another. Shifting the block of elements instead of swapping preserves the original order of equal keys, at the cost of extra writes."}},{"@type":"Question","name":"How do you sort in descending order instead?","acceptedAnswer":{"@type":"Answer","text":"Reverse the comparison inside the inner loop. Testing whether array[j] is greater than array[index] tracks the largest remaining value, so each pass moves the maximum forward and the finished array runs from high to low."}},{"@type":"Question","name":"Can the algorithm be written recursively in Java?","acceptedAnswer":{"@type":"Answer","text":"Yes. A recursive method finds the minimum of the current subarray, swaps it into the front, then calls itself on the remainder. The comparison count is unchanged, but the call stack adds O(n) space, so the loop form is preferred."}},{"@type":"Question","name":"Which coding mistakes break the implementation most often?","acceptedAnswer":{"@type":"Answer","text":"The frequent faults are forgetting to reset index to i at the start of each pass, starting the inner loop at i instead of i + 1, and swapping array[j] rather than array[index], which loses track of the smallest value."}},{"@type":"Question","name":"Does Java's Arrays.sort() use selection sort internally?","acceptedAnswer":{"@type":"Answer","text":"No. Arrays.sort() applies a dual-pivot quicksort to primitives and TimSort to objects, with an insertion-style sort on tiny partitions. Selection sort appears in teaching material and hand-written code rather than in the standard library."}}]}],"@id":"https://www.guru99.com/selection-sorting-java.html#schema-1155377","isPartOf":{"@id":"https://www.guru99.com/selection-sorting-java.html#webpage"},"publisher":{"@id":"https://www.guru99.com/#organization"},"inLanguage":"en-US","mainEntityOfPage":{"@id":"https://www.guru99.com/selection-sorting-java.html#webpage"}}]}
```
