[Java] 选择排序算法 - 亲手敲的供参考 →→→→→进入此内容的聊天室

来自 , 2021-03-14, 写在 Java, 查看 126 次.
URL http://www.code666.cn/view/f0adc883
  1. package selectionSort;
  2.  
  3. public class SelectionSortImpl {
  4.  
  5.         /*
  6.          * 每一趟从待排序的数据元素中选出最小(或最大)的一个元素,顺序放在已排好序的数列的最后,直到全部待排序的数据元素排完。 选择排序是不稳定的排序方法
  7.          */
  8.         public static int[] selectionSort(int[] arr) {
  9.  
  10.                 int len = arr.length;
  11.                 int temp = Integer.MAX_VALUE;
  12.                 int idx = -1;
  13.                 for (int j = 0; j < len; j++) {
  14.                         for (int i = j; i < len; i++) {
  15.                                 if (i == j) {
  16.                                         temp = arr[i];
  17.                                         idx = i;
  18.                                 } else if (arr[i] < temp) {
  19.                                         temp = arr[i];
  20.                                         idx = i;
  21.                                 }
  22.                         }
  23.                         /*
  24.                          * every time put the smallest element in the sorted order list via
  25.                          * exchanging the the first unsorted element with the mark smallest
  26.                          * element
  27.                          */
  28.                         if (idx != j) {
  29.                                 arr[idx] = arr[j];
  30.                                 arr[j] = temp;
  31.                         }
  32.                 }
  33.                 return arr;
  34.         }
  35. }
  36.  
  37. package selectionSort;
  38.  
  39. import java.util.Arrays;
  40.  
  41.  
  42. public class TestSelectionSort {
  43.  
  44.         public static void main(String[] args) {
  45.                 int[] arr = new int[] { 9, 8, 7, 6, 5, 4, 2, 1 };
  46.                 System.out.println("The unsorted array is                          : "
  47.                                 + Arrays.toString(arr));
  48.                 System.out.println("The sorted array with bubble sort algorithm is : "
  49.                                 + Arrays.toString(SelectionSortImpl.selectionSort(arr)));
  50.         }
  51.  
  52. }
  53.  
  54. /*运行结果
  55. The unsorted array is                                            : [9, 8, 7, 6, 5, 4, 2, 1]
  56. The sorted array with selection sort algorithm is : [1, 2, 4, 5, 6, 7, 8, 9]
  57. */
  58.  
  59.  
  60.  

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

这儿你可以回复上面这条便签

captcha