Alternatively, bubble, insertion sort

Selection Sort
principle is the number of the latter with the number of each comparison, a down find a maximum, and then continue the cycle, the time complexity of the code is n ^ 2 as follows oh

import java.util.*;
class test1{
    public static void main(String[] args){
        int [] arr={3,4,8,0,9,34,21};
    }
    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[i]>arr[j]){
                     swap(arr,i,j);
                 }
             }
             System.out.print(Arrays.toString(arr));
        }
    }
    public static void swap(int [] arr,int m,int n){
        for(int i=0;i<arr.length;i++){
            if(arr[m]>arr[n]){
              int temp=0;
              temp=arr[m];
              arr[m]=arr[n];
              arr[n]=temp;
            }
        }
    }
}

Bubble sort
and selection sort are not the same is that, the first bubble and second comparing and then recycled, the time complexity is n ^ 2, look at the code

import java.util.*;
class test1{
    public static void main(String[] args){
        int [] arr={3,4,8,0,9,34,21};
    }
    public static void selectSort(int [] arr){
        for(int i=0;i<arr.length-1;i++){//少比一轮
             for(int j=0;j<arr.length-1-i;j++){//少比一轮和避免角标越界
                 if(arr[j]>arr[j+1]){
                     swap(arr,i,j);//这里这样写主要是为了节省内存,因为用函数,用完就弹栈了
                 }
             }
             System.out.print(Arrays.toString(arr));
        }
    }
    public static void swap(int [] arr,int m,int n){
        for(int i=0;i<arr.length;i++){
            if(arr[m]>arr[n]){
              int temp=0;
              temp=arr[m];
              arr[m]=arr[n];
              arr[n]=temp;
            }
        }
    }
}

Insertion sort
insertion sort like the sort of the opposite of choice, the choice and better than the bubble

import java.util.*;
class test1{
    public static void main(String[] args){
        int [] arr={3,4,8,0,9,34,21};
    }
    public static void selectSort(int [] arr){
        for(int i=1;i<arr.length;i++){
            int e=arr[i];
            int j;
             for( j=i;j>0&&arr[j-1]>e;j--){
                         arr[j]=arr[j-1];
             }
                  arr[j]=e;
             System.out.print(Arrays.toString(arr));
        }
    }
    public static void swap(int [] arr,int m,int n){
        for(int i=0;i<arr.length;i++){
            if(arr[m]>arr[n]){
              int temp=0;
              temp=arr[m];
              arr[m]=arr[n];
              arr[n]=temp;
            }
        }
    }
}

To be continued

Published 15 original articles · won praise 0 · Views 290

Guess you like

Origin blog.csdn.net/qq_37244548/article/details/104377801