Home >Java >javaTutorial >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. 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!