选择排序算法(Selection Sort)

【选择排序算法基本思想和案例】
选择排序:
         每一趟从待排序的数据元素中选出最小(或者最大)的一个元素,顺序放在已经排好序的数列的后面,直到全部待排序的数据元素排完。
 案例:
         初始数组资源【63    4    24    1    3    15】
         第一趟排序后【15    4    24    1    3】 63
         第二趟排序后【15    4     3    1】 24   63
         第三趟排序后【  1    4     3】15   24   63
         第四趟排序后【  1    3】 4    15   24   63
         第五趟排序后【  1】 3     4   15   24   63
算法主要代码:
   
   
  1. // 定义方法实现选择排序
  2. public static void selectionSort(int[] array) {
  3. int count = 1;
  4. while (count >= 1) {
  5. int index = 0;
  6. int max = array[0];
  7. for (int i = 1; i <= array.length - count; i++) {
  8. if (max < array[i]) {
  9. max = array[i];
  10. index = i;
  11. }
  12. }
  13. int temp = array[array.length - count];
  14. array[array.length - count] = max;
  15. array[index] = temp;
  16. count++;
  17. if (count == array.length - 1) {
  18. break;
  19. }
  20. }
  21. }
  22. }
案例:
   
   
  1. public class SelectSort {
  2. public static void main(String[] args) {
  3. int[] array = {63, 4, 24, 1, 3, 15};
  4. System.out.println("排序前:");
  5. for (int i : array) {
  6. System.out.print(i + "\t");
  7. }
  8. System.out.println();
  9. selectionSort(array);
  10. System.out.println("排序后:");
  11. for (int i : array) {
  12. System.out.print(i + "\t");
  13. }
  14. }
  15. // 定义方法实现选择排序
  16. public static void selectionSort(int[] array) {
  17. int count = 1;
  18. while (count >= 1) {
  19. int index = 0;
  20. int max = array[0];
  21. for (int i = 1; i <= array.length - count; i++) {
  22. if (max < array[i]) {
  23. max = array[i];
  24. index = i;
  25. }
  26. }
  27. int temp = array[array.length - count];
  28. array[array.length - count] = max;
  29. array[index] = temp;
  30. count++;
  31. if (count == array.length - 1) {
  32. break;
  33. }
  34. }
  35. }
  36. }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值