-
July 20th, 2022, 07:09 AM
#1
In C, bubble sorting causes a garbage value error.
So I've lately started learning data structures in C. Let's get back to my issue.
Here is the code for my Bubble Sort Algorithm (Taken from Scaler Academy)
Code:
#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;
}
When I have my array set up like this: int arr[]=2,4,1,3,5,2,6,10;
ex : int arr[]={2,4,1,3,5,2,6,10,13}; output : int arr[]={2,4,1,3,5,2,6,10};
It sorts correctly, but when I increase the number of items in arr by one, it begins throwing trash values.
Last edited by VictorN; October 14th, 2023 at 01:13 AM.
Reason: Web link was removed.
-
July 20th, 2022, 09:06 AM
#2
Re: In C, bubble sorting causes a garbage value error.
Originally Posted by Nathan D
So I've lately started learning data structures in C. Let's get back to my issue.
...
It sorts correctly, but when I increase the number of items in arr by one, it begins throwing trash values.
Define "it begins throwing trash values".
And, BTW, I have texted your code and didn't see any "throwing"
Victor Nijegorodov
-
July 20th, 2022, 12:20 PM
#3
Re: In C, bubble sorting causes a garbage value error.
look at the case when i = len - 1 and j=i
Then j = len - 1
you are accessing arr[j+1] = arr[len-1+1] = arr[len]
which is outside the bounds of the array.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|