Home >Java >javaTutorial >How to code a selection sort algorithm using Java
How to use Java to write the code of the selection sort algorithm
Selection sort is a simple and intuitive sorting algorithm. Its working principle is to start from the data to be sorted each time. Select the smallest (or largest) element and put it at the end of the sorted data until all the data is exhausted. The following will introduce how to use Java to write the code of the selection sort algorithm and give specific code examples.
Code example:
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; } } // 交换arr[i]和arr[minIndex] int temp = arr[i]; arr[i] = arr[minIndex]; arr[minIndex] = temp; } } public static void main(String[] args) { int[] arr = {64, 25, 12, 22, 11}; System.out.println("排序前的数组:"); for (int num : arr) { System.out.print(num + " "); } selectionSort(arr); System.out.println(" 排序后的数组:"); for (int num : arr) { System.out.print(num + " "); } } }
Analysis:
The above code defines a class named SelectionSort
, which contains a static methodselectionSort
To implement the selection sorting algorithm. In the selectionSort
method, two nested loops are used. The outer loop controls the current position to be sorted, and the inner loop is used to find the subscript of the smallest element of the unsorted part. Then exchange the element at the current to-be-sorted position with the smallest element. By continuously repeating this process until all elements are sorted.
In the main
method, we create an integer array arr
and initialize some random elements. Then output the array before sorting and call the selectionSort
method to sort the array. Finally, the sorted array is output again.
The above is a code example of using Java to write a selection sort algorithm. I hope it will be helpful for you to understand the selection sort algorithm and become familiar with Java programming!
The above is the detailed content of How to code a selection sort algorithm using Java. For more information, please follow other related articles on the PHP Chinese website!