选择排序的实现及优化【Java版】

1、基本实现

/**
*实现选择排序
*方法一
*O(n^2)
*/

public class SelectSort {
    public void selectSort(int []arr,int n) {
        for(int i=0;i<n;i++) {
            for(int j=i+1;j<n;j++) {
                if(arr[j]<arr[i]) {
                    swap(arr,i,j);
                }
            }
        }
    }
    private void swap(int[] arr, int i, int j) {
        if(i!=j) {
            int temp =arr[j];
            arr[j]=arr[i];
            arr[i]=temp;
        }
    }
}

2、优化

public class SelectSort2 {
    public void selectSort(int []arr,int n) {
        for(int i=0;i<n;i++) {
            int minpoint=i;
            for(int j=i+1;j<n;j++) {
                if(arr[j]<arr[minpoint]) {
                    minpoint=j;
                }
            }
            if(arr[i]>arr[minpoint])
               swap(arr, minpoint, i);
        }
    }
    private void swap(int[] arr, int i, int j) {
        if(i!=j) {
            int temp =arr[j];
            arr[j]=arr[i];
            arr[i]=temp;
        }
    }
}

猜你喜欢

转载自blog.csdn.net/yulutian/article/details/79512350