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.
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
[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<stdio.h> #include<stdlib.h> #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<n-1; i++) { int min_index = i; //找出第i小的数所在的位置 for(int j=i+1; j<n; j++) { if(a[j] < a[min_index]) { min_index = j; } } //将第i小的数,放在第i个位置;如果刚好,就不用交换 if( i != min_index) { int temp = a[i]; a[i] = a[min_index]; a[min_index] = temp; } } } int main() { int num[N] = {89, 38, 11, 78, 96, 44, 19, 25}; select_sort(num, N); for(int i=0; i<N; i++) printf("%d ", num[i]); printf("\n"); system("pause"); return 0; }
Rendering:
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!