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.
Re: In C, bubble sorting causes a garbage value error.
Quote:
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"
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.