-
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.
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
|