We are learning arrays and I just came around bubble sorting.
I wrote the following code to sort the array in ascending order but there is a problem.
I can't find it out but I know there's a problem.
I have found the correct code but I still don't understand why this is not working.
My Code
int a;
int i;
int temp;
int value[5] = { 5, 4, 3, 2, 1 };
for (i = 0; i < 5; i++) {
if (value[i] > value[i + 1]) {
temp = value[i];
value[i] = value[i + 1];
value[i + 1] = temp;
}
}
for (a = 0; a < 5; a++) {
printf(" %d ", value[i]);
}
When
i == 4
you access the position 5 withvalue[i+1]
and it is not yours.You are accessing unreserved memory.
Your Code Has Multiple Problems ,
First And Foremost You are printing the array elements after that sorting that you did with
value[i]
and you are running loop with variablea
.You are Accessing
value[5]
, which is not yours.The Biggest Problem, is that you have not understood Bubblesort completely. In Bubble Sort The Loop is run multiple times, until in a loop there are no member to swap, that is when you stop looping.
This is What Wikipedia Says
See The Below Presentation To Understand How Bubble Sort Works.See the Loop Run again and again, till there are no member left to swap.
So You Need To Run The Loop Multiple Times Until No Member Are There To Swap, You Can Do So By Having a new variable
count
, initially initialised to1
at the start, and before each loop starts, it get initialised to0
, if in the loop, Swap statement executes then, it changes to1
, and again the loop is executed because count is1
, if in the last pass, its value does not changes to1
because all member are now sorted, so loop does not run again.