top of page
Search

Java Selection Sort Algorithm for Arrays

We previously discussed how to sort a Java array using Bubble Sort however that is only one of many sorting algorithms for arrays. Selection Sort is a straightforward sorting algorithm that is easy to remember conceptually. For this technique, our approach will be to iterate through the array to find the smallest element, and swap it with the current index.


First, create two variables to keep track of the index of the next minimum element, and for use in the 'swapping' step

  int n;      //index variable
  int temp;   //swap variable

Now we will use nested for-loops. The outer for-loop will keep track of how much of the array has been sorted (i.e. will inform the index variable). This will ensure that we do not search the already sorted elements when looking for the next minimum element.

 for(int i = 0; i<arr.length; i++){
    n = i;

The inner for-loop will be used to search for the next minimum element

    for(int j = i+1; j<arr.length; j++){

        if(arr[j]<arr[n]){        //checks if arr[j] is next min
            n = j;                //n stores index of min value
         }
    }

And now we return to the outer for-loop for the swap.

    temp = arr[n];
    arr[n] = arr[i];
    arr[i] = temp;
  }


That's all there is to it!!


See you soon!

Bronwyn


nested for loop: a for-loop contained within another for-loop, allowing the program to run an iteration within another iteration.

 
 
 

Recent Posts

See All
Java Switch Case

Ever needed to write a million if-else statements to the point where your brain is breaking and you're about an inch away from throwing...

 
 
 

Comments


bottom of page