DEV Community

Tanuja V
Tanuja V

Posted on β€’ Edited on

3 3 1 2 1

Selection Sort in Java (With Intuition + Dry run + Code)

Why the name selection sort ?

Selection sort gets its name from the way it selects the smallest (or largest, depending on the implementation) element from the unsorted portion of the array and moves it to its correct position in the sorted portion of the array. This process is repeated until all elements are sorted.

Algorithm:

  1. We start by iterating through the array from index 0 to n-1, where n is the length of the array.
  2. For each iteration, we assume that the element at the current index is the smallest (min_index = i).
  3. We then iterate through the rest of the array starting from i+1.
  4. If we find an element smaller than the current smallest element (A[min_index]), we update min_index to the index of the new smallest element.
  5. After completing the inner loop, we swap the element at index i with the smallest element found (A[min_index]).
  6. This process repeats until the entire array is sorted.

I will show the working of Selection sort but make sure to dry run using pen & paperπŸ“

selection-sort

Code


public class SelectionSort {

    public static void main(String[] args) {

        int arr[] = {7, 4, 10, 8, 3, 1};

        int len = arr.length;

        int i=0, j=0;

        for(i=0; i<len-1; i++) {
            int min = i;
            for(j=i; j<len; j++) {
                if(arr[j]<arr[min])
                    min = j;
            }

            int temp = arr[i];
            arr[i] = arr[min];
            arr[min] = temp;
        }


        for(int k=0; k<len; k++) {
            System.out.print(arr[k]+" ");
        }
    }

}
Enter fullscreen mode Exit fullscreen mode

Time Complexity:

  • Best Case: O(n^2)
  • Worst Case: O(n^2)

Space Complexity:

O(1)

Wrapping Up:

Now, congrats, you've learnt selection sort πŸ₯³πŸ‘
Thanks for reading :)
Feel free to comment and like the post if you found it helpful
Follow for more 🀝 && Happy Coding πŸš€

If you enjoy my content, support me by following me on my other socials:
https://linktr.ee/tanujav7

AI Agent image

How to Build an AI Agent with Semantic Kernel (and More!)

Join Developer Advocate Luce Carter for a hands-on tutorial on building an AI-powered dinner recommendation agent. Discover how to integrate Microsoft Semantic Kernel, MongoDB Atlas, C#, and OpenAI for ingredient checks and smart restaurant suggestions.

Watch the video πŸ“Ί

Top comments (2)

Postmark Image

20% off for developers shipping features, not fixing email

Build your product without worrying about email infrastructure. Our reliable delivery, detailed analytics, and developer-friendly API let you focus on shipping features that matter.

Start free

πŸ‘‹ Kindness is contagious

DEV works best when you're signed inβ€”unlocking a more customized experience with features like dark mode and personalized reading settings!

Okay