zoukankan      html  css  js  c++  java
  • 选择排序

    <<<<<<<<<<<<--------->>>>>>>>>>>>>>>>

    选择排序是一种简单直观的排序算法,而且它不会占用额外的内存空间。

      原理:遍历元素找到一个最小或最大的元素,把它放在第一个位置,然后再从剩余的元素中找到最小或最大的元素,把它放在第二个位置,依次下去,直到完成排序。

      时间复杂度为O(n2)

      思路:

        给定一个数组 s[]

        第一趟排序,在待排序的n个元素中选出最小的一个,将它与s[1]交换;

        第二趟排序,在剩下的待排序元素s[2]~s[n]中选出最小的一个数据,将它与s[2]交换;

        ...

        以此类推

        第n-1趟排序,在待排序的s[n-1]~s[n]中选出最小的数据,将它与s[n-1]交换

        排序完成。

      动图演示效果:

      Java代码实现:

     1 public class SelectionSort {
     2     public static void main(String[] args) {
     3         int[] arr = new int[] { 5, 3, 6, 2, 10, 2, 1 };
     4         selectSort(arr);
     5         for (int i = 0; i < arr.length; i++) {
     6             System.out.print(arr[i] + " ");
     7         }
     8     }
     9     public static void selectSort(int[] arr) {
    10         for (int i = 0; i < arr.length - 1; i++) {
    11             int minIndex = i;     // 用来记录最小值的索引位置,默认值为i
    12             for (int j = i ; j < arr.length; j++) {
    13                 if (arr[j] < arr[minIndex]) {
    14                     minIndex = j;     // 遍历 i~length 的值,找到其中最小值的位置
    15                 }
    16             }
    17             if (i != minIndex) {     // 交换当前索引 i 和最小值索引 minIndex 两处的值
    18                 int temp = arr[i];
    19                 arr[i] = arr[minIndex];
    20                 arr[minIndex] = temp;
    21             }      // 执行完一次循环,当前索引 i 处的值为最小值,直到循环结束即可完成排序
    22         }
    23     }
    24 }
  • 相关阅读:
    Android属性动画ObjectAnimator的使用1
    通过Android反编译技术研究国内陌生人社交即时通讯的技术方案
    滴滴出行开源项目doraemonkit食用指南
    Android开发利器之pidcat
    Spinner在Dialog中的使用效果
    python抓取知识星球精选帖,制作为pdf文件
    [设计模式]观察者模式
    C语言实现进度条
    [设计模式]策略模式
    线程链表与线程切换
  • 原文地址:https://www.cnblogs.com/HuiH/p/11665410.html
Copyright © 2011-2022 走看看