使用函数实现选择或冒泡排序:定义选择排序函数void selectsort(int a[],int n)
时间: 2024-01-24 11:17:17 浏览: 24
好的,以下是使用选择排序算法实现的 C++ 代码:
```
void selectsort(int a[], int n) {
int i, j, min_idx;
for (i = 0; i < n - 1; i++) {
min_idx = i;
for (j = i + 1; j < n; j++) {
if (a[j] < a[min_idx]) {
min_idx = j;
}
}
// Swap the minimum element with the first element
int temp = a[min_idx];
a[min_idx] = a[i];
a[i] = temp;
}
}
```
这个函数接收一个整数数组 `a` 和数组长度 `n` 作为参数,将数组按升序排序。算法的核心是在每一轮循环中找到当前未排序部分中的最小元素,然后与未排序部分的第一个元素交换位置。
你也可以使用类似的方式编写冒泡排序函数,只需要将算法实现替换为冒泡排序即可。
相关问题
使用函数实现选择或冒泡排序:定义选择排序函数void selectsort(int a[],int n) 或者冒泡排序函数viod bubblesort(int a[],int n)对数组a中的元素进行排序,主函数中输入数组元素和元素个数,调用排序函数对数组元素升序排序后输出结果
以下是选择排序和冒泡排序的实现,可以根据需要选择其中之一:
选择排序:
```c++
void selectsort(int a[], int n) {
for (int i = 0; i < n-1; i++) {
int min_idx = i;
for (int j = i+1; j < n; j++) {
if (a[j] < a[min_idx]) {
min_idx = j;
}
}
if (min_idx != i) {
swap(a[i], a[min_idx]);
}
}
}
```
冒泡排序:
```c++
void bubblesort(int a[], int n) {
for (int i = 0; i < n-1; i++) {
bool flag = false;
for (int j = 0; j < n-i-1; j++) {
if (a[j] > a[j+1]) {
swap(a[j], a[j+1]);
flag = true;
}
}
if (!flag) {
break; // 如果没有发生交换,则已经有序
}
}
}
```
在主函数中,可以先读入数组元素和元素个数,然后调用排序函数进行排序,最后输出排序后的结果。示例代码如下:
```c++
#include <iostream>
using namespace std;
void selectsort(int a[], int n);
void bubblesort(int a[], int n);
int main() {
int n;
cout << "请输入数组元素个数:";
cin >> n;
int a[n];
cout << "请输入数组元素:";
for (int i = 0; i < n; i++) {
cin >> a[i];
}
// selectsort(a, n); // 调用选择排序函数进行排序
bubblesort(a, n); // 调用冒泡排序函数进行排序
cout << "排序结果为:";
for (int i = 0; i < n; i++) {
cout << a[i] << " ";
}
cout << endl;
return 0;
}
```
c语言使用函数实现选择或冒泡排序:定义选择排序函数void selectsort(int a[],int n) 或者冒泡排序函数viod bubblesort(int a[],int n)对数组a中的元素进行排序,主函数中输入数组元素和元素个数,调用排序函数对数组元素升序排序后输出结果
以下是选择排序函数和冒泡排序函数的实现:
选择排序函数:
```c
void selectsort(int a[], int n) {
int i, j, min_idx;
for (i = 0; i < n - 1; i++) {
min_idx = i;
for (j = i + 1; j < n; j++) {
if (a[j] < a[min_idx]) {
min_idx = j;
}
}
if (min_idx != i) {
int temp = a[i];
a[i] = a[min_idx];
a[min_idx] = temp;
}
}
}
```
冒泡排序函数:
```c
void bubblesort(int a[], int n) {
int i, j;
for (i = 0; i < n - 1; i++) {
for (j = 0; j < n - i - 1; j++) {
if (a[j] > a[j + 1]) {
int temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
}
}
```
在主函数中,可以按照以下方式输入数组元素和元素个数,调用排序函数进行排序并输出结果:
```c
#include <stdio.h>
int main() {
int a[100], n, i;
printf("请输入元素个数:");
scanf("%d", &n);
printf("请输入数组元素:");
for (i = 0; i < n; i++) {
scanf("%d", &a[i]);
}
// 调用选择排序函数或冒泡排序函数进行排序
// selectsort(a, n);
bubblesort(a, n);
printf("排序后的结果为:");
for (i = 0; i < n; i++) {
printf("%d ", a[i]);
}
printf("\n");
return 0;
}
```