Home>Article> How to implement selection sort algorithm in C language

How to implement selection sort algorithm in C language

清浅
清浅 Original
2019-04-09 11:53:02 39510browse

The steps to implement the selection sorting method: first find a minimum number and swap it to the front; then find the smallest number among the remaining numbers and swap it to the front of the remaining numbers; finally repeat this step until Just line up all the numbers.

How to implement selection sort algorithm in C language

Steps to implement the selection sorting method: find a minimum number and swap it to the front, then find the smallest number among the remaining numbers and swap it to the rest Count at the front and repeat this step until all the numbers are arranged

How to implement selection sort algorithm in C language

[Recommended course:C Language Tutorial

Selection sorting method is a relatively common method in C language. Its sorting efficiency is higher than the bubble method and the algorithm is not complicated.

The idea of selection sorting method is:

1. Find a minimum number and swap it to the front.

2. Among the remaining numbers, find the smallest one and swap it to the front of the remaining numbers.

3. Repeat step 2 until all the numbers have been arranged.

Obviously, for an array containing N numbers, the process also requires N-1 times (0 <= i < N-1).

The way to find a minimum number and swap it to the front is:

First use the first number among the remaining numbers (the serial number is i) as the base , use variable k to record its serial number, and the subsequent numbers are compared with the base in turn. If it is smaller than the base, use k to record its serial number (note: do not exchange at this time). When all numbers are compared with the base, k What is stored in is the serial number of the smallest number, and then it is swapped to the front (exchanged only now). In the above process, data is only exchanged once, that is, data is only exchanged once per trip.

Example:

#include #include #define N 8 void select_sort(int a[],int n); //选择排序实现 void select_sort(int a[],int n)//n为数组a的元素个数 { //进行N-1轮选择 for(int i=0; i
      

Rendering:

How to implement selection sort algorithm in C language

Summary: The above is the entire content of this article. I hope it will be useful to you. Everyone is helpful

The above is the detailed content of How to implement selection sort algorithm in C language. For more information, please follow other related articles on the PHP Chinese website!

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