Java implements simple sorting algorithm

Bubble Sort:

 1 //java实现冒泡排序
 2 
 3 import java.util.Arrays;
 4 
 5 public class BubbleSort{
 6     public static void main (String[] args){
 7         int [] a = {423,0,52,65,4,3,2,1287,43};
 8         bubleSort(a);
 9         System.out.println(Arrays.toString(a));
10         
11     }
12     
13     public static int[] bubleSort(int [] A){
14         for(int i = 0;i<A.length-1;i++)
15             for(int j = i+1;j < A.length;j++)
16                 if(A[i] > A[j]){
17                     int tmp = A[i];
18                     A[i] = A[j];
19                     A[j] = tmp;
20                 }
21         return A;
22     }
23 }

Selection sort:

// Implement selection sort 
import java.util.Arrays;

public class SelectSort
{
    public static void main(String[]args)
    {
        int [] a = {42,1,23,12,3,45,234,612,34};
        selectSort(a);
        System.out.println(Arrays.toString(a));
    }
    
    public static int [] selectSort(int A[])
    {
        for(int i = 0;i < A.length-1;i++)
            for(int j = i+1;j < A.length;j++)
            {    
                int temp = A[i];
                if(A[i] > A[j])
                {
                    temp = A[i];
                    A[i] = A[j];
                    A[j] = temp;
                }
            }
            return A;
    }
    
}

Code experience:

The for loop seems to be very simple, but it is actually very difficult to loop. In for(int i = 0; i < A; i++), the first assignment is performed, then the code is executed, then the addition is performed, and finally the review is performed.

A represents the number of loops, A-1 represents the end point, the for loop should be interpreted as: starting from i, looping A times, i from 0 to A-1.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325873403&siteId=291194637