Home >Backend Development >C++ >How to use selection sort algorithm in C++
How to use the selection sort algorithm in C
Selection sort is a simple and intuitive sorting algorithm. Its principle is to continuously select the minimum value among the remaining elements. , and places it at the end of the sorted sequence. This article will introduce how to use C language to implement the selection sort algorithm, and provide specific code examples to help readers better understand and use the algorithm.
The basic idea of selection sorting is as follows:
The following is a code example using C language to implement selection sorting:
#include <iostream> using namespace std; // 选择排序函数 void selectionSort(int arr[], int n) { for (int i = 0; i < n-1; i++) { int minIndex = i; // 保存最小值的索引 for (int j = i+1; j < n; j++) { if (arr[j] < arr[minIndex]) { minIndex = j; // 更新最小值的索引 } } // 将最小值与当前位置的元素交换 if (minIndex != i) { int temp = arr[i]; arr[i] = arr[minIndex]; arr[minIndex] = temp; } } } // 打印数组元素 void printArray(int arr[], int size) { for (int i = 0; i < size; i++) { cout << arr[i] << " "; } cout << endl; } int main() { int arr[] = {64, 25, 12, 22, 11}; int n = sizeof(arr) / sizeof(arr[0]); cout << "排序前的数组:"; printArray(arr, n); selectionSort(arr, n); cout << "排序后的数组:"; printArray(arr, n); return 0; }
Run the above code, the output result is as follows:
排序前的数组:64 25 12 22 11 排序后的数组:11 12 22 25 64
Through the above code example, we can See the specific implementation process of the selection sort algorithm. The time complexity of this algorithm is O(n^2), where n represents the size of the array to be sorted. Although selection sort is not very efficient on large data sets, it is still a simple, understandable and effective sorting algorithm for small arrays or mostly ordered arrays.
To summarize, this article introduces how to use C language to implement the selection sort algorithm and provides detailed code examples. It is hoped that readers can master the implementation principle of the selection sort algorithm by reading this article, and be able to flexibly use this algorithm in actual development.
The above is the detailed content of How to use selection sort algorithm in C++. For more information, please follow other related articles on the PHP Chinese website!