Select sort
- Idea: Start with 0 index, compare with the following elements in turn, and put the smaller ones forward. After the first time, the minimum value appears at the minimum index. The other things are the same to get a good sorted array.
- For example
1. The original array
2. After the first sorting
3. After the second sorting
4. After the third sorting
5. After the fourth sorting
- Rule
1. The first time is to compare with others starting from zero index
2. The second time is to compare with others from the beginning
...
3. The last time is to compare the elements of array length-2 with the elements of array length-1
Code
public class Test {
public static void main(String[] args) {
int[] array=new int[]{
24,69,80,57,13};
System.out.println("排序前");
printArray(array);
selectSort(array);
System.out.println("排序后");
printArray(array);
}
public static void selectSort(int[] arr){
for(int i=0;i<arr.length-1;i++){
for(int j=i+1;j<arr.length;j++) {
if (arr[j] < arr[i]) {
int temp = arr[i];
arr[i] = arr[j ];
arr[j] = temp;
}
}
}
}
public static void printArray(int[] arr){
System.out.print("[");
for (int i=0;i<arr.length;i++){
if(i==arr.length-1){
System.out.print(arr[i]);
}
else{
System.out.print(arr[i]+",");
}
}
System.out.println("]");
}
Java introductory basic learning (1)
Java introductory basic learning (2)
Java introductory basic learning (3)
Common objects of
advanced java (1) Bubble sorting of advanced java