用户注册



邮箱:

密码:

用户登录


邮箱:

密码:
记住登录一个月忘记密码?

发表随想


还能输入:200字
云代码 - java代码库

选择排序算法 - 亲手敲的供参考

2013-08-02 作者: 中国人在美国举报

[java]代码库

package selectionSort;
 
public class SelectionSortImpl {
 
    /*
     * 每一趟从待排序的数据元素中选出最小(或最大)的一个元素,顺序放在已排好序的数列的最后,直到全部待排序的数据元素排完。 选择排序是不稳定的排序方法
     */
    public static int[] selectionSort(int[] arr) {
 
        int len = arr.length;
        int temp = Integer.MAX_VALUE;
        int idx = -1;
        for (int j = 0; j < len; j++) {
            for (int i = j; i < len; i++) {
                if (i == j) {
                    temp = arr[i];
                    idx = i;
                } else if (arr[i] < temp) {
                    temp = arr[i];
                    idx = i;
                }
            }
            /*
             * every time put the smallest element in the sorted order list via
             * exchanging the the first unsorted element with the mark smallest
             * element
             */
            if (idx != j) {
                arr[idx] = arr[j];
                arr[j] = temp;
            }
        }
        return arr;
    }
}
 
package selectionSort;
 
import java.util.Arrays;
 
 
public class TestSelectionSort {
 
    public static void main(String[] args) {
        int[] arr = new int[] { 9, 8, 7, 6, 5, 4, 2, 1 };
        System.out.println("The unsorted array is                          : "
                + Arrays.toString(arr));
        System.out.println("The sorted array with bubble sort algorithm is : "
                + Arrays.toString(SelectionSortImpl.selectionSort(arr)));
    }
 
}
 
/*运行结果
The unsorted array is                                            : [9, 8, 7, 6, 5, 4, 2, 1]
The sorted array with selection sort algorithm is : [1, 2, 4, 5, 6, 7, 8, 9]
*/


网友评论    (发表评论)


发表评论:

评论须知:

  • 1、评论每次加2分,每天上限为30;
  • 2、请文明用语,共同创建干净的技术交流环境;
  • 3、若被发现提交非法信息,评论将会被删除,并且给予扣分处理,严重者给予封号处理;
  • 4、请勿发布广告信息或其他无关评论,否则将会删除评论并扣分,严重者给予封号处理。


扫码下载

加载中,请稍后...

输入口令后可复制整站源码

加载中,请稍后...