用swift实现,1到10000中取200个随机数,使冒泡排序法排序并输入
时间: 2024-05-13 08:20:55 浏览: 14
以下是用Swift实现的代码:
```
func bubbleSort(_ arr: inout [Int]) {
let n = arr.count
for i in 0..<n {
for j in 0..<n-i-1 {
if arr[j] > arr[j+1] {
arr.swapAt(j, j+1)
}
}
}
}
var arr = [Int]()
for i in 1...10000 {
arr.append(i)
}
for i in 0..<200 {
let randomIndex = Int.random(in: i..<arr.count)
arr.swapAt(i, randomIndex)
}
bubbleSort(&arr)
print(arr)
```
首先定义了一个冒泡排序的函数bubbleSort,然后生成一个包含1到10000的数组arr。接着用一个for循环,每次从剩余的数中随机选一个数,与当前数交换位置,这样就得到了200个随机数。最后调用bubbleSort函数进行排序,并打印结果。
相关问题
c语言十个随机数的冒泡排序法
好的,以下是c语言实现十个随机数的冒泡排序法的代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define N 10 // 数组长度
int main(void)
{
int arr[N]; // 存储随机数的数组
int i, j, temp;
// 生成随机数
srand((unsigned)time(NULL));
for (i = 0; i < N; i++) {
arr[i] = rand() % 100; // 生成 0~99 的随机数
}
// 输出排序前的数组
printf("排序前的数组:\n");
for (i = 0; i < N; i++) {
printf("%d ", arr[i]);
}
printf("\n");
// 冒泡排序
for (i = 0; i < N-1; i++) {
for (j = 0; j < N-i-1; j++) {
if (arr[j] > arr[j+1]) {
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
// 输出排序后的数组
printf("排序后的数组:\n");
for (i = 0; i < N; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
```
以上代码中,使用srand()函数和rand()函数生成10个随机数,然后使用冒泡排序法将数组从小到大排序,并输出排序前后的数组。
10个随机数的冒泡排序法。c语言
好的,这是一个使用 C 语言实现的随机数的冒泡排序算法:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define SIZE 10
void bubble_sort(int arr[], int size) {
int i, j, temp;
for (i = 0; i < size - 1; i++) {
for (j = 0; j < size - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
int main() {
int arr[SIZE];
int i;
srand((unsigned)time(NULL)); // 初始化随机数种子
for (i = 0; i < SIZE; i++) {
arr[i] = rand() % 100; // 生成 0~99 的随机整数
}
printf("排序前的数组为:\n");
for (i = 0; i < SIZE; i++) {
printf("%d ", arr[i]);
}
printf("\n");
bubble_sort(arr, SIZE);
printf("排序后的数组为:\n");
for (i = 0; i < SIZE; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
```
代码中使用了 `srand()` 函数初始化随机数种子,然后用 `rand()` 函数生成 0~99 的随机整数。另外,`bubble_sort()` 函数实现了冒泡排序算法,用于对随机数数组进行排序。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](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)