java选择排序法

来源:互联网 发布:h5多人联网游戏源码 编辑:程序博客网 时间:2024/06/06 00:43

选择排序法,每一趟从待排序的元素中选出最小(或最大)的一个元素,顺序放在已排序好的数列最后,直到全部数据元素排完。

package com.demo;public class Demo {public static int[] orderBySelect(int[] nums, String str){/** * Ordered by descend */if(str.equalsIgnoreCase("desc")){for(int i = 0; i < nums.length; i++ )for (int j = i + 1; j < nums.length; j++) {if(nums[i] < nums[j]){int temp = nums[i];nums[i] = nums[j];nums[j] = temp;}}}/** * Ordered by ascend */else if(str.equalsIgnoreCase("esc")){for (int i = 0; i < nums.length; i++) {for (int j = i + 1; j < nums.length; j++) {if(nums[i] > nums[j]){int temp = nums[j];nums[j] = nums[i];nums[i] = temp;}}}}return nums;}public static void main(String[] args) throws Exception {System.out.println("从大到小:");int nums1[] = orderBySelect(new int[]{1, 3, 5, 2, 56, 23}, "desc");for (int i = 0; i < nums1.length; i++) {System.out.print(nums1[i] + " ");}System.out.println();System.out.println("从小到大:");int nums2[] = orderBySelect(new int[]{1, 3, 5, 2, 56, 23}, "esc");for (int i = 0; i < nums2.length; i++) {System.out.print(nums2[i] + " ");}}}
从大到小:56 23 5 3 2 1 从小到大:1 2 3 5 23 56 



0 0
原创粉丝点击