Home > php教程 > php手册 > body text

经典算法学习直接选择排序

WBOY
Release: 2016-06-13 08:42:09
Original
984 people have browsed it

经典算法学习——直接选择排序

直接选择排序和直接插入排序类似,都将数据分为有序区和无序区,所不同的是直接插入排序是将无序区的第一个元素直接插入到有序区以形成一个更大的有序区;而直接选择排序是从无序区选一个最小的元素直接放到有序区的最后。示例代码上传至: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;
}</stdio.h>
Copy after login
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!