Home  >  Article  >  Backend Development  >  Classic Algorithm Learning - Direct Selection Sorting_PHP Tutorial

Classic Algorithm Learning - Direct Selection Sorting_PHP Tutorial

WBOY
WBOYOriginal
2016-07-12 08:54:41874browse

Classic Algorithm Learning - Direct Selection Sorting

Direct selection sort is similar to direct insertion sort. Both divide the data into ordered area and unordered area. The difference is that direct insertion sort inserts the first element of the unordered area directly into the ordered area to form A larger ordered area; direct selection sorting selects the smallest element from the unordered area and places it directly at the end of the ordered area. Sample code uploaded to: https://github.com/chenyufeng1991/SelectSort

The algorithm is described as follows:
(1) Initially, the array is all unordered and the area is a[0...n-1]. Let i = 0.

(2) Select the smallest element in the unordered area a[i...n-1] and exchange it with a[i]. After the exchange, a[0...i] forms an ordered area.

(3) i and repeat the second step until i == n-1, the sorting is completed.

The implementation is as follows:

//
//  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>

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1119560.htmlTechArticleClassic algorithm learning - direct selection sorting Direct selection sorting and direct insertion sorting are similar, both divide the data into order The difference between the area and the unordered area is that direct insertion sorting takes the unordered area...
Statement:
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