Java - 选择排序算法 [英] Java - Selection Sort Algorithm

查看:112
本文介绍了Java - 选择排序算法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对选择排序有一些疑问。我有点困惑。

I have some questions about selection sort.I'm a little bit confused.

 int [] arr = {5,4,3,2,1}; // This is my array
    int min = 0;

    for(int i = 0;i<arr.length;i++)
    {
        //Assume first element is min
        min = i;//Selection sort algorithm says that find the minimum in the
                // array, but first element is not minimum.What's point here?
        for(int j = i + 1;j<arr.length;j++)
        {
            int temp = arr[i];
            arr[i] = arr[j];
            arr[j] = temp;
            System.out.println(arr[i]);//I print the in ascending order 
        }
    }

输出为:

4
3
2
1
4
3
2
4
3
4

怎么了?

推荐答案

选择排序是关于在循环的每一步中找到最小值。你没有找到最小值(可能是if语句),只需简单地交换内循环中的值即可。所以你实际上没有进行排序。

selection sort is about finding the min value in each step of loop. you didn't find out the min value (by if statement maybe), just simply exchange the value in your inner loop. so you actually didn't do a sort.

基于你的实施进行修正:

correction based on your implementation:

final int[] arr = { 5, 4, 3, 2, 1 }; // This is my array
    int min;
    for (int i = 0; i < arr.length; i++) {
        // Assume first element is min
        min = i;
        for (int j = i + 1; j < arr.length; j++) {
            if (arr[j] < arr[min]) {
                min = j;

            }
        }
        if (min != i) {
            final int temp = arr[i];
            arr[i] = arr[min];
            arr[min] = temp;
        }
        System.out.println(arr[i]);// I print the in ascending order
    }

这应该给你输出:

1
2
3
4
5

这篇关于Java - 选择排序算法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆