选择排序法c++语言程序
时间: 2024-01-02 19:23:07 浏览: 30
以下是使用选择排序法的C++程序示例:
```cpp
#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;
}
}
swap(arr[i], arr[minIndex]);
}
}
int main() {
int arr[] = {64, 25, 12, 22, 11};
int n = sizeof(arr)/sizeof(arr[0]);
selectionSort(arr, n);
cout << "Sorted array: ";
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
cout << endl;
return 0;
}
```
相关问题
冒泡法排序c++语言程序
以下是C++语言实现冒泡排序的程序:
```cpp
#include <iostream>
using namespace std;
int main() {
int n, i, j, temp;
int a[2000];
cin >> n;
for (i = 0; i < n; i++) {
cin >> a[i];
}
for (i = 0; i < n - 1; i++) {
for (j = 0; j < n - i 1; j++) {
if (a[j] > a[j + 1]) {
temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
}
for (i = 0; i < n; i++) {
cout << a[i] << " ";
}
return 0;
}
```
插入排序c++语言程序
插入排序是一种简单直观的排序算法,它的工作原理是通过构建有序序列,对于未排序数据,在已排序序列中从后向前扫描,找到相应位置并插入。在C++中,插入排序可以这样实现:
```cpp
#include <iostream>
// 插入排序函数
void insertionSort(int arr[], int n) {
for (int i = 1; i < n; ++i) {
int key = arr[i];
int j = i - 1;
// 将arr[j]大于key的元素向右移动
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j = j - 1;
}
// 插入元素
arr[j + 1] = key;
}
}
int main() {
int arr[] = {9, 7, 5, 11, 12, 2, 14, 3, 10};
int n = sizeof(arr) / sizeof(arr);
std::cout << "Original array: ";
for (int i = 0; i < n; ++i) {
std::cout << arr[i] << " ";
}
insertionSort(arr, n);
std::cout << "\nSorted array: ";
for (int i = 0; i < n; ++i) {
std::cout << arr[i] << " ";
}
return 0;
}
```
在这个程序中,`insertionSort`函数接收一个整数数组和它的大小作为参数,然后通过循环和比较过程对数组进行排序。`main`函数则展示了如何调用这个排序函数,并输出排序前后的数组。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![text/x-c++](https://img-home.csdnimg.cn/images/20210720083646.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)