美文网首页
选择排序

选择排序

作者: wayneinyz | 来源:发表于2017-11-02 12:11 被阅读7次
    public class SelectionSort {
    
        /*
        在要排序的一组数中,找出最小的一个数与第一个位置的数交换;
        然后在剩下的数中,再找出最小的与第二个位置的数交换;
        如此循环,直到倒数第二个数和最后一个数比较为止。
         */
        public static void selectionSort(int[] a) {
            for (int i = 0; i < a.length; i++) {
                int min = i;
                for (int j = i+1; j < a.length; j++) {
                    if (a[j] < a[min])
                        min = j;
                }
    
                int temp = a[i];
                a[i] = a[min];
                a[min] = temp;
            }
        }
    
        public static void main(String[] args) {
            int[] a = new int[] {2, 4, 7, 5, 11, 3, 1, 9, 7, 8, 10, 6, -1, 0};
            selectionSort(a);
            for (int i = 0; i < a.length; i++) {
                System.out.print(a[i] + " ");
            }
        }
    
    }
    

    相关文章

      网友评论

          本文标题:选择排序

          本文链接:https://www.haomeiwen.com/subject/ewyopxtx.html