简体   繁体   English

冒泡排序程序返回随机数

[英]Bubble-sort program returns random numbers

I'm learning C and my bubble sort code returns a random number sometimes (although sometimes it does returns the correct array numbers).我正在学习 C,我的冒泡排序代码有时会返回一个随机数(尽管有时它会返回正确的数组编号)。

For example, it should print {0, 1, 3, 10}.例如,它应该打印 {0, 1, 3, 10}。 But sometimes prints things like {-487420160, 0, 1, 3} or {-1484260208, 0, 1, 3} (only the first number changes, the other are correct).但有时会打印 {-487420160, 0, 1, 3} 或 {-1484260208, 0, 1, 3} 之类的东西(只有第一个数字改变,其他是正确的)。

This is the code:这是代码:

#include <stdio.h>

int main(){

//array and variables
int arr[] = {1, 3, 0, 10};
int len = sizeof(arr)/ sizeof(int);
int j = 0;
int i = 0;

//print original array
printf("ORIGINAL ARRAY: \n");
printf("{");
for (int x = 0; x < len; x ++){
    printf("%d", arr[x]);
    if (x < len-1){
        printf(", ");
    }
}
printf("}\n");

//sorting
for ( i = 0;i < len; i++){
    for (j = 0 ;j < len; j ++){
        if(arr[j] > arr[j+1]){
            int temporal = arr[j];
            arr[j] = arr[j+1];
            arr[j+1] = temporal;
        }
    }
}

//print sorted array
printf("BUBBLE-SORTED ARRAY: \n");
printf("{");
for (int y = 0; y < len; y ++){
    printf("%d", arr[y]);
    if (y < len-1){
        printf(", ");
    }
}
printf("}\n");

return 0;
}

Do anybody know why or can help me improve the code?有人知道为什么或可以帮助我改进代码吗?

In place of the for(j=0:j<len;j++) change to for(j=0:j<len-1;j++) :代替for(j=0:j<len;j++)更改为for(j=0:j<len-1;j++)

for ( i = 0;i < len; i++){
    for (j = 0 ;j < len; j ++){// here instead of len use len-1
        if(arr[j] > arr[j+1]){
            int temporal = arr[j];
            arr[j] = arr[j+1];
            arr[j+1] = temporal;
        }
    }
}

Now, in bubble sort we usually compare until the end, but in your case when j=len then j+1 is a random number which has no existence and there is no element.现在,在冒泡排序中,我们通常比较到最后,但在您的情况下,当j=len时, j+1是一个不存在且没有元素的随机数。

Make the following change and you will get the solution.进行以下更改,您将获得解决方案。

#include <stdio.h>

int main(){

//array and variables
int arr[] = {1, 3, 0, 10};
int len = sizeof(arr)/ sizeof(int);
int j = 0;
int i = 0;
int x=0;
int y=0;

//print original array
printf("ORIGINAL ARRAY: \n");
printf("{");
for (x = 0; x < len; x ++){
    printf("%d", arr[x]);
    if (x < len-1){
    printf(", ");
    }
}
printf("}\n");

//sorting
for ( i = 0;i < len; i++){
    for (j = 0 ;j < len-1; j++){// Here is the change, len has been changed to len-1
    if(arr[j] > arr[j+1]){
        int temporal = arr[j];
        arr[j] = arr[j+1];
        arr[j+1] = temporal;
    }
    }
}

//print sorted array
printf("BUBBLE-SORTED ARRAY: \n");
printf("{");
for (y = 0; y < len; y ++){
    printf("%d", arr[y]);
    if (y < len-1){
        printf(", ");
    }
}
printf("}\n");

return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM