zoukankan      html  css  js  c++  java
  • 经典算法学习——直接选择排序

           直接选择排序和直接插入排序相似,都将数据分为有序区和无序区,所不同的是直接插入排序是将无序区的第一个元素直接插入到有序区以形成一个更大的有序区。而直接选择排序是从无序区选一个最小的元素直接放到有序区的最后。演示样例代码上传至:https://github.com/chenyufeng1991/SelectSort

    算法描写叙述例如以下:
    (1)初始时,数组全为无序区为a[0...n-1]。

    令i = 0。

    (2)在无序区a[i...n-1]中选取一个最小的元素,将其与a[i]交换。

    交换之后a[0...i]就形成了一个有序区。

    (3)i++并反复第二步。直到i == n-1,排序完毕。

    实现例如以下:

    //
    //  main.c
    //  SelectSort
    //
    //  Created by chenyufeng on 16/2/3.
    //  Copyright © 2016年 chenyufengweb. All rights reserved.
    //
    
    #include <stdio.h>
    
    void selectSort(int *a,int n);
    void swap(int *a,int *b);
    
    int main(int argc, const char * argv[]) {
    
    
        int a[] = {6,1,4,9,0,3};
        selectSort(a,6);
        for (int i = 0; i < 6 ; i++) {
            printf("%d ",a[i]);
        }
    
        return 0;
    }
    
    void selectSort(int *a,int n){
    
        int i,j,minIndex;
        for (i = 0; i < n; i++) {
    
            minIndex = i;
            //从无序区中找出最小的数
            for (j = i + 1; j < n; j++) {
                if (a[j] < a[minIndex]) {
                    //不断记录最小数的下标;
                    minIndex = j;
                }
            }
            //把无序区中最小的数放到有序区的最后一个位置。
            swap(&a[i],&a[minIndex]);
        }
    }
    
    void swap(int *a,int *b){
    
        int temp;
        temp = *a;
        *a = *b;
        *b = temp;
    }


         说明一下。直接选择排序的时间复杂度为O(n^2),空间复杂度为O(1)。是一种不稳定的排序。




    本文參考:http://blog.csdn.net/morewindows/article/details/6671824

  • 相关阅读:
    神奇的flex布局
    reset、revert、rebase
    Vue.filter过滤器
    moment.js时间格式化总结
    Vue之组件大全
    过滤器filter
    Vue之animate
    Vue之axios
    Mac OS系统上测试PHP代码前的准备工作 | 使用XAMPP搭建Apache服务器的步骤
    Python中的标识符、关键字、变量、语句、注释、模块
  • 原文地址:https://www.cnblogs.com/brucemengbm/p/7279734.html
Copyright © 2011-2022 走看看