【发布时间】:2020-05-14 03:20:06
【问题描述】:
所以最近我一直在学习 C 中的数据结构。现在让我们来解决我的问题
这是我的冒泡排序算法代码:
#include <conio.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
void swap(int *p, int *q) {
int temp = *p;
*p = *q;
*q = temp;
}
int main() {
int arr[] = {2, 4, 1, 3, 5, 2, 3, 6, 4}; // see below for arr
int len = sizeof(arr) / sizeof(int);
for (int i = len - 1; i >= 0; i--) {
for (int j = 0; j <= i; j++) {
if (arr[j] < arr[j + 1]) {
swap(&arr[j], &arr[j + 1]);
}
}
}
for (int m = 0; m < len; m++) {
printf("%d\t", arr[m]);
}
return 0;
}
当我的数组类似于:int arr[]={2,4,1,3,5,2,6,10}; 时,它的排序很完美,但是当我将 arr 中的值数量增加一时,它开始提供垃圾值。
例如:int arr[]={2,4,1,3,5,2,6,10,13};
输出:int arr[]={2,4,1,3,5,2,6,10};
详细解答高度赞赏
【问题讨论】:
-
将 int arr[]={2,4,1,3,5,2,6,10,13} 设置为全局对我有用
-
您需要访问Bubble Sort - Wikipedia 并查看算法(尤其是优化冒泡排序部分)。您的算法不是冒泡排序,而是其中一种变体。
-
还要问问自己,“为什么我要包含
conio.h, math.h和stdlib.h?” “我在使用什么需要这些标头?” -
我知道,那是我上次的代码;P
标签: c algorithm data-structures computer-science bubble-sort