Home >Java >javaTutorial >How to implement selection sort algorithm using java

How to implement selection sort algorithm using java

WBOY
WBOYOriginal
2023-09-19 09:46:41680browse

How to implement selection sort algorithm using java

How to use Java to implement the selection sort algorithm

The selection sort algorithm is a simple and intuitive sorting algorithm. Its basic idea is to find the minimum among unsorted elements. (or largest) element, placing it at the end of the sorted sequence. Thus, an ordered sequence is gradually constructed.

Below we will introduce how to implement the selection sort algorithm in the form of Java code examples.

Code implementation:

public class SelectionSort {

  public static void selectionSort(int[] arr) {
    int n = arr.length;
    
    for (int i = 0; i < n-1; i++) {
        int minIndex = i;
        for (int j = i+1; j < n; j++) {
            if (arr[j] < arr[minIndex]) {
                minIndex = j;
            }
        }
        
        // 将最小元素与当前位置元素交换
        int temp = arr[minIndex];
        arr[minIndex] = arr[i];
        arr[i] = temp;
    }
  }
  
  public static void main(String[] args) {
    int[] arr = {64, 25, 12, 22, 11};
    selectionSort(arr);
    
    System.out.println("排序后的数组:");
    for (int i = 0; i < arr.length; i++) {
        System.out.print(arr[i] + " ");
    }
  }
}

Code analysis:

  • selectionSort method is used to implement the selection sorting algorithm, parameters arr is the integer array to be sorted.
  • n The variable represents the length of the array.
  • The outer loop traverses from 0 to n-1 to determine the minimum value of the current round.
  • The inner loop traverses from i 1 to n and finds the minimum index of the unsorted part.
  • After finding the minimum value index through comparison, place the minimum element at the end of the sorted sequence by exchanging the position of the elements. The
  • main method demonstrates how to use the selection sort algorithm to sort an array and output the sorted results.

Code running results:

排序后的数组:11 12 22 25 64 

Selection sort is a simple but inefficient sorting algorithm with a time complexity of O(n^2). However, its advantages are simple implementation and clear thinking. It can be used as a basis for other sorting algorithms and for understanding how sorting algorithms work.

I hope the above code demonstration can help you understand the implementation process of the selection sort algorithm. If you have any questions, feel free to ask me.

The above is the detailed content of How to implement selection sort algorithm using java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn