1、分别采用数组和指针,编写一段程序,其功能实现一串数字的从 大到小排列:
时间: 2023-03-15 08:53:12 浏览: 55
我们可以使用快速排序算法来实现。 使用数组: int array[10]; //定义一个数组 for (int i=0; i<10; i++) {
array[i] = rand() % 100; //随机生成10个数
} qsort(array, 10, sizeof(int), compare); //使用快速排序算法 //compare函数为比较函数,比较数组元素大小 使用指针: int *pArray = (int *)malloc(10 * sizeof(int)); //分配内存 for (int i=0; i<10; i++) {
pArray[i] = rand() % 100; //随机生成10个数
} qsort(pArray, 10, sizeof(int), compare); //使用快速排序算法 //compare函数为比较函数,比较数组元素大小 free(pArray); //释放内存
相关问题
用C语言编写程序:编写一个函数sort,使用指针的方法对一个数组a[10],实现从大到小的排序。
好的,下面是代码实现:
```c
#include <stdio.h>
void sort(int *a, int n) {
int i, j, tmp;
for (i = 0; i < n - 1; i++) {
for (j = i + 1; j < n; j++) {
if (*(a + i) < *(a + j)) { // 如果前面的元素小于后面的元素
tmp = *(a + i); // 交换两个元素的值
*(a + i) = *(a + j);
*(a + j) = tmp;
}
}
}
}
int main() {
int arr[10] = {3, 5, 2, 1, 4, 6, 8, 9, 7, 10};
int *p = arr; // 定义指针指向数组的首地址
sort(p, 10); // 调用排序函数
for (int i = 0; i < 10; i++) {
printf("%d ", *(p + i)); // 打印排序后的数组元素
}
return 0;
}
```
运行结果为:
```
10 9 8 7 6 5 4 3 2 1
```
其中,`*(a + i)` 表示指针指向的数组元素的值,`a` 是数组的首地址,`i` 是数组下标。排序函数中使用了选择排序算法,将数组元素从大到小排序。
用C++编写一个能对字符串数组由小到大进行排序的小程序
以下是使用C++实现字符串数组排序的示例程序:
```c++
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
int main() {
const int n = 5; // 字符串数组大小
string strs[n] = {"hello", "world", "apple", "orange", "banana"}; // 待排序字符串数组
// 对字符串数组进行排序
sort(strs, strs + n);
// 输出排序后的字符串数组
for (int i = 0; i < n; i++) {
cout << strs[i] << endl;
}
return 0;
}
```
在上面的程序中,我们使用了`sort`函数来对字符串数组进行排序。该函数需要传入两个迭代器表示需要排序的范围,这里我们使用了数组的指针和数组长度来表示。
运行程序后,输出结果为:
```
apple
banana
hello
orange
world
```
可以看到,字符串数组已经按字典序由小到大排好序了。