排序算法(三):简单选择排序算法-Java实现

排序算法(三):简单选择排序算法-Java实现

简单选择算法是除堆排序的另外一种选择排序算法,其也是一种不稳定的排序算法,平均时间复杂度为O(N2),空间时间复杂度为O(1)

简单选择算法相对比较简单,并且易于理解,具体排序算法思路如下:

  1. 选择数组中最小的一个元素与array[i]交换,始终是将数组分为aray[0]...array[i] 有序和array[i+1]...array[array.length-1]无序两部分
  2. 将无序中最小值放到array[i+1]处

实现代码如下:

 1 public class SelectSort {
 2 
 3     public static void main(String[] args) {
 4         int[] array = new int[]{5, 3, 6, 2, 1, 9, 4, 8, 7};
 5         SelectSort selectSort = new SelectSort();
 6         selectSort.selectSort(array);
 7         for (int i = 0; i < array.length; i++) {
 8             System.out.print(array[i] + " ");
 9         }
10     }
11 
12     public void selectSort(int[] array) {
13         if (array == null || array.length == 0) return;
14 
15         for (int i = 0; i < array.length; i++) {
16             // 默认最小为i
17             int min = i;
18             // 此循环主要是选择出来最小的元素
19             for (int j = i + 1; j < array.length; j++) {
20                 if (array[min] > array[j]) {
21                     min = j;
22                 }
23             }
24 
25             // 将两个元素交换
26             if (min != i) {
27                 swap(array, i, min);
28             }
29 
30         }
31     }
32 
33     private void swap(int[] array, int i, int j) {
34         //  有可能溢出
35         array[i] = array[i] + array[j];
36         array[j] = array[i] - array[j];
37         array[i] = array[i] - array[j];
38     }
39 }

 

posted @ 2017-10-09 01:05  房杰  阅读(202)  评论(0编辑  收藏  举报