So recently I have been Learning data structures in C . Now let's come to my problem
Here is my Code of Bubble Sort Algo :
#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 my array is like : int arr[]={2,4,1,3,5,2,6,10};
it's sorting perfectly but when i increase the number of values in arr
by one , it starts giving garbage value.
ex : int arr[]={2,4,1,3,5,2,6,10,13};
output : int arr[]={2,4,1,3,5,2,6,10};
Detailed Anwer Highly Appreciated
When j=i
and i=len-1
(which is allowed in the loop over j
) the check:
if(arr[j]<arr[j+1]){
swap(&arr[j],&arr[j+1]);
}
goes out of bounds for arr
. Additionally even for smaller values of i
the last check is not needed. To fix your code make the loop condition j < i
instead of j <= i
.