C语言中的冒泡排序
我是一名初学者 C 程序员。我试图编写一个程序来返回数组的最高值。为此,您应该首先对数组进行排序。为了对数组进行排序,我使用了冒泡排序方法,在进行冒泡排序后,我的计划是返回已排序数组的第一个元素。这样它将返回数组的最高值。但当我运行代码时,它正在打印垃圾值。这是代码。
#include <stdio.h>
int bub(int arr[]);
int main(){
//creating an array
int arr[] = {23,4,65,76,87};
/*calling the function. Here I am printing it. because when I just call the function it is not
returning anything*/
int abs = bub(arr);
printf("%d",abs);
}
// defining function
int bub(int arr[]){
// creating a loop to go till the end of the array
for (int i = 0 , len = sizeof(arr[i]) / sizeof(int) ; i<len ; i++){
for (int j = 0;j<i;j++){
// swaping if the the value is greater than the next value of the array
if (arr[j]>arr[j+1]){
// swaping the values
arr[j] = arr[j]^arr[j+1];
arr[j+1] = arr[j]^arr[j+1];
arr[j] = arr[j]^arr[j+1];
// printing the first value to get the highest value
printf("%d",arr[0]);
}
}
}
}
为什么它返回打印垃圾值?有没有更好的方法来找到数组的最高值?或者这段代码有什么可以改进的地方吗?
请回复。
I am a beginner c programmer. I was trying to make a program which will return the highest value of an array. For that you should first sort the array. And for sorting the array I used Bubble sort method, and after doing bubble sort my plan was to return the first element of the sorted array. So that it will return the highest value of the array. But the moment I run the code It is printing garbage values. Here is the code.
#include <stdio.h>
int bub(int arr[]);
int main(){
//creating an array
int arr[] = {23,4,65,76,87};
/*calling the function. Here I am printing it. because when I just call the function it is not
returning anything*/
int abs = bub(arr);
printf("%d",abs);
}
// defining function
int bub(int arr[]){
// creating a loop to go till the end of the array
for (int i = 0 , len = sizeof(arr[i]) / sizeof(int) ; i<len ; i++){
for (int j = 0;j<i;j++){
// swaping if the the value is greater than the next value of the array
if (arr[j]>arr[j+1]){
// swaping the values
arr[j] = arr[j]^arr[j+1];
arr[j+1] = arr[j]^arr[j+1];
arr[j] = arr[j]^arr[j+1];
// printing the first value to get the highest value
printf("%d",arr[0]);
}
}
}
}
why is it return printing garbage values? Is there any better way to find the highest value of an array?. Or is there anything that I can improve in this code?
please reply.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果你想使用冒泡排序来找到最高值,下面是我修改过的程序。请注意,您正在使用“>”为了在这种情况下进行比较,第一个元素将是最低的,我更改了它,最好在主函数中声明数组的大小并将其作为参数传递给要使用它的函数。
另一种更简单的方法是只需遍历数组一次即可找到最高或最低值。
像这样
If you to use bubble sort to find highest value, below is the program I have modified. Note that you are using '>' to compare in such case the first element will be lowest , I changed it and it is better to declare the size of array in main function and pass it to functions as a parameter where you want to use it.
Another simpler way is to just traverse through the array once to find highest or lowest value.
Like this