Home >Java >javaTutorial >Guidance and Examples: Learn to implement the selection sort algorithm in Java
Java Selection Sorting Method Code Writing Guide and Examples
Selection sort is a simple and intuitive sorting algorithm. The idea is to select from unsorted elements each time The smallest (or largest) elements are swapped until all elements are sorted. This article will provide a code writing guide for selection sorting, and attach specific Java sample code.
The following is a sample code for the selection sort method written in Java language:
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 : arr) { System.out.print(i + " "); } } }
In the above sample code, we first define a selectionSort
method, used to implement the selection sorting algorithm. Then, create an array to be sorted arr
in the main
method, and pass it to the selectionSort
method for sorting. Finally, the sorted results are output by looping through the array.
The above is the detailed content of Guidance and Examples: Learn to implement the selection sort algorithm in Java. For more information, please follow other related articles on the PHP Chinese website!