Program work 17. Selection Sort in Java

每轮循环将该轮最小的数放在前面已排好的数的末尾


最好最坏平均复杂度是O(n*n)


Pseudocode:

selectionSort (arr)
{
    Find the smallest card. Swap it with the first card.
    Find the second-smallest card. Swap it with the second card.
    Find the third-smallest card. Swap it with the third card.
    Repeat finding the next-smallest card, and swapping it into the correct position until the array is sorted.
}

Java:

package ncku.cdc.sorting;

import java.util.Random;

public class SelectionSort {
  private int[] sequence;
  
  public SelectionSort(int size, int range) {
    sequence = new int[size];
    Random rand = new Random();
    for (int i = 0; i < size; i++) {
      sequence[i] = rand.nextInt(range);
    }
  }
  
  public static void main(String[] args) {
    int size = Integer.valueOf(args[0]);
    int range = Integer.valueOf(args[1]);
    SelectionSort selection = new SelectionSort(size, range);

    System.out.println("before selectionSort:");
    SortingTools.validation(selection.getSequence(), 0);

    selection.selectionSort(selection.getSequence());
    
    System.out.println("after selectionSort:");
    SortingTools.validation(selection.getSequence(), 0);
  }
  
  public void selectionSort(int[] arr) {
    int len = arr.length;
    int i = 0;
    int j;
    int min;
    while (i < len) {
      min = i;
      for (j = i + 1; j < len; j++) {
        if (arr[j] < arr[min]) { min = j; }
      }
      swap(arr, i++, min);
    }
  }
  
  private void swap(int[] arr, int i, int j) {
    int t = arr[i];
    arr[i] = arr[j];
    arr[j] = t;
  }
  
  public int[] getSequence() {
    return sequence;
  }
}


程序输入: 35 200. 表示生成长度为35, 数字范围从[0, 200)的数组

程序输出:

before selectionSort:
143 38 58 102 182 19 65 65 31 113 94 18 107 167 182 15 51 74 176 2 42 160 11 81 0 102 95 169 3 86 41 64 31 105 64 
after selectionSort:
0 2 3 11 15 18 19 31 31 38 41 42 51 58 64 64 65 65 74 81 86 94 95 102 102 105 107 113 143 160 167 169 176 182 182


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值