Java - Selection Sort Algorithm

insertion sort in java
selection sort in java programming simplified
selection sort in c++
bubble sort in java
selection sort java ascending
selection sort code
merge sort java
selection sort java arraylist

I have some questions about selection sort.I'm a little bit confused.

 int [] arr = {5,4,3,2,1}; // This is my array
    int min = 0;

    for(int i = 0;i<arr.length;i++)
    {
        //Assume first element is min
        min = i;//Selection sort algorithm says that find the minimum in the
                // array, but first element is not minimum.What's point here?
        for(int j = i + 1;j<arr.length;j++)
        {
            int temp = arr[i];
            arr[i] = arr[j];
            arr[j] = temp;
            System.out.println(arr[i]);//I print the in ascending order 
        }
    }

Output is :

4
3
2
1
4
3
2
4
3
4

What's wrong ?

selection sort is about finding the min value in each step of loop. you didn't find out the min value (by if statement maybe), just simply exchange the value in your inner loop. so you actually didn't do a sort.

correction based on your implementation:

final int[] arr = { 5, 4, 3, 2, 1 }; // This is my array
    int min;
    for (int i = 0; i < arr.length; i++) {
        // Assume first element is min
        min = i;
        for (int j = i + 1; j < arr.length; j++) {
            if (arr[j] < arr[min]) {
                min = j;

            }
        }
        if (min != i) {
            final int temp = arr[i];
            arr[i] = arr[min];
            arr[min] = temp;
        }
        System.out.println(arr[i]);// I print the in ascending order
    }

this should give you output:

1
2
3
4
5

Java Program for Selection Sort, The selection sort algorithm sorts an array by repeatedly finding the minimum element (considering ascending order) from unsorted part and putting it at the beginning. The algorithm maintains two subarrays in a given array. 1) The subarray which is already sorted. 2) Remaining subarray which is unsorted. Java Program for Selection Sort The selection sort algorithm sorts an array by repeatedly finding the minimum element (considering ascending order) from unsorted part and putting it at the beginning.

Correct:

public class Test {

public static void main(String args[]){
    int[] arr = {5,4,3,2,1}; // This is my array
    int min = 0;

    for(int i = 0;i<arr.length;i++)
    {
        //Assume first element is min
        min = i;
        for(int j = i + 1;j<arr.length;j++)
        {
            if(arr[j] < arr[min]) { min = j;}
        }
        int temp = arr[i];
        arr[i] = arr[min];
        arr[min] = temp;
        System.out.println(arr[i]);//I print the in ascending order 
    }
}

}

About the min part: it just refers to the index of whatever is the current min. You move on down the array until you meet the new min, and set min to that index. So 5 is the minimum number [min =0] until you see 4 [so now min =1] but then you compare 3 to whatever is stored at 4 [when min=1] and then realize that you should set min=2.... etc. etc.

Selection Sort in Java, We can create a java program to sort array elements using selection sort. In selection sort algorithm, we search for the lowest element and arrange it to the proper  Implement Selection sort Java  We will discuss a couple of methods to Implement Selection Sort In Java Algorithm. The compiler has been added so you can easily execute the given programs, alongside suitable examples and samples outputs added for Selection Sort In Java, For More Sorting Programs in Java Visit here.

Your question appears to be in your comment

min = i;//Selection sort algorithm says that find the minimum in the
        // array, but first element is not minimum.What's point here?

The point of that is you can assume the first one you're checking is the lowest just so you have a place to start from. After all, it might not be the minimum over all, but of the one's you've checked in this iteration, it's the lowest so far!

Implement selection sort in java., The selection sort is a combination of searching and sorting. During each pass, the unsorted element with the smallest (or largest) value is moved to its proper  Program: Implement selection sort in java. The selection sort is a combination of searching and sorting. During each pass, the unsorted element with the smallest (or largest) value is moved to its proper position in the array. The number of times the sort passes through the array is one less than the number of items in the array.

You should first find the minimum instead of assuming the first element is the minimum

int[] array = {5, 4, 3, 2, 1};
for ( int i = 0; i < array.length; i++ ) {

  //find minimum, starting from index i
  int minIndex = i;
  int min = array[i];
  for ( int j = i + 1; j < array.length; j++ ) {
    if ( array[ j ] < min ) {
      minIndex = j;
      min = array[j];
    }
  }

  // now move the smallest element to the front, and the element at index i to the index of the minimal element
  int temp = array[ i ];
  array[ i ] = min;
  array[ minIndex ] = temp;
}

Selection Sort in Java, 2. Algorithm Overview. Selection Sort begins with the element in the 1st position of an unsorted array and scans through subsequent elements  Program: Implement selection sort in java. The selection sort is a combination of searching and sorting. During each pass, the unsorted element with the smallest (or largest) value is moved to its proper position in the array. The number of times the sort passes through the array is one less than the number of items in the array.

You should start by assuming that the first element is the smallest one, then iterate over the array and if you find a smaller element, remember that position and assume that is the smallest one. When you get to the end of the array you should know the position of the smallest value. Switch that value with the value at the first position. Now the smallest value is first. Start at next position, assume that is the smallest value, iterate over the rest of the array... (I think you get the idea.

Example:

3,1,2

Assume 3 (pos 1) is smallest. Compare with position 2, 1 < 3, so assume position 2 has smallest value. Compare with position 3, 3 < 1. Since we are at the end switch smallest with first position. (position 1 and 2)

1,3,2

Now, since position 1 is done, start with position 2. Assume 3 (position 2) is the smallest value. Compare with position 3 (2). 2 < 3, so assume position 3 has smallest value. Since we are at the end of the array we switch position 2 and 3

1,2,3

Done

Java Selection sort example – Mkyong.com, A full example to demonstrate the use of Selection sort algorithm to sort a simple data set. SelectionSortExample.java. package com.mkyong;  The selection sort algorithm sorts an array by repeatedly finding the minimum element (considering ascending order) from unsorted part and putting it at the beginning. The algorithm maintains two subarrays in a given array. 1) The subarray which is already sorted. 2) Remaining subarray which is unsorted.

Java - Selection Sort Algorithm, selection sort is about finding the min value in each step of loop. you didn't find out the min value (by if statement maybe), just simply exchange the value in your​  In selection sort, the smallest value among the unsorted elements of the array is selected in every pass and inserted to its appropriate position into the array. First, find the smallest element of the array and place it on the first position.

Java: SelectionSort animated demo with code, Animated demo tutorial on the Selection Sort algorithm, with example Java code Duration: 7:11 Posted: Jan 3, 2015 Comparable Interface. If you have your own types, it may get cumbersome implementing a separate sorting algorithm for each one. That's why Java provides an interface allowing you to use Collections.sort() on your own classes. To do this, your class must implement the Comparable<T> interface, where T is your type,

Java program to implement selection sort, Selection sort is a simple sorting algorithm. This sorting algorithm is an in-place comparison-based algorithm in which the list is divided into two  Selection Sort. The selection sort algorithm sorts an array by repeatedly finding the minimum element (considering ascending order) from unsorted part and putting it at the beginning. The algorithm maintains two subarrays in a given array. 1) The subarray which is already sorted.

Comments
  • you're swapping on every minimum - isn't this bubble sort, not selection sort?
  • fair enough, upon further inspection it isn't bubble sort as yes it does always swap neighbors. And this isn't quite insertion sort either. This is a unique approach on selection sort, for sure, and is different enough that it, to me, would deserve some kind of title like "variation of selection sort".
  • @glowcoder in my opinion, this is selection sort. selection sort is always aussming the 1st is the min, then find the min from the rest elements, if the found min.idx<>original(first).idx, swap. what I did is, every time a new min found, do swap. saving the space of the variable "min". but did more swapping. I edited the code, now it should be exactly same as text book. (didn't test, should work) bubble sort is not like this, even though it does swap too. it swap two neighbours.
  • -1 Just giving someone the code to fix their homework assignment without even an explanation is not going to be useful at all. Even if you are correct, you're not helping them understand, nor is their question to fix their code in the first place... it's just to understand something about the algorithm.
  • I added comments later... if you had just waited 2 minutes
  • Also I disagree that knowing the answer isn't useful, but that's just a personal opinion. Ever seen practice exams without an answer key?
  • I see your changes (which could use some work, but they're alright), but I can't remove my downvote unless an edit is registered. :(
  • While this code snippet may solve the question, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. Please also try not to crowd your code with explanatory comments, this reduces the readability of both the code and the explanations!
  • Please note if you want to promote your own product/blog you must disclose your affiliation in the answer, otherwise your answer may be flagged as spam. Please read How to not be a spammer
  • I've edited in some disclosure now (before I bothered to check whether you've been active recently). But please pay attention to what @CalvT says.
  • While this may solve the issue it does not explain why.
  • While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value. You should also try to format the code properly.
  • Please add some explanations also.
  • Thanks for the comment. I have added explanation
  • I actually meant not like explanations for the term, it can be found in google, but your code, if it's something original :).