Stack around Variable a is corrupted - arrays

#include<stdio.h>
int main(void)
{
int array[10] = { 10,2,9,4,5,6,7,8,3,1 };
/*Implementing Bubble Sort */
int temp;
for (int i = 0; i < 9; i++)
{
for (int j = 0; j < 10 - i; j++)
{
if (array[j] > array[j + 1])
{
temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
for (int i = 0; i < 10; i++)
{
printf("%d ", array[i]);
}
}
When I try to run the program I'm getting values sorted but one value has some garbage value and the dialogue box appears that stack around variable is corrupted in VS 2019. In some other compiler I'm getting 0 in place of 10 in compiler.

The inner for .loop
for (int j = 0; j < 10 - i; j++)
{
if (array[j] > array[j + 1])
{
temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
invokes undefined behavior because when j is equal to 9 for the first iteration of the outer loop that is when i is equal to 0 the index in the expression array[j + 1] can be equal to 10 that results in accessing the memory beyond the array.
Rewrite the loop like
for (int j = 1; j < 10 - i; j++)
{
if (array[j-1] > array[j])
{
temp = array[j-1];
array[j-1] = array[j];
array[j] = temp;
}
}

You can you this logic slightly edited from yours.
#include<stdio.h>
int main(void)
{
int array[10] = { 10,2,9,4,5,6,7,8,3,1 };
/*Implementing Bubble Sort */
int temp;
for (int i = 0; i < 10; i++)
{
for (int j = i; j < 10; j++)
{
if (array[i] > array[j])
{
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
for (int i = 0; i < 10; i++)
{
printf("%d ", array[i]);
}
}

Related

Bubble sort in C

I was trying to implement bubble sort algorithm to sort a 10 element array. I've tried writing the code below and it doesn't seem wrong, but it doesn't sort the elements at all.
Could someone give me a hand?
This is the code:
`
#include <stdio.h>
#define DIM 10
int main() {
int arr[DIM] = {1, 5, 6, 8, 7, 9, 3, 2, 4, 10};
int tmp;
puts("Original array: ");
for (int i = 0; i < DIM; i++) {
printf("%3d", arr[i]);
}
// Bubble sort
for (int i = 0; i < DIM - 1; ++i) {
for (int j = 0; j < DIM - i - 1; ++j) {
// Compare two elements and swap if first > second
// Use of tmp variable (temporary)
if (arr[i] > arr[i + 1]) {
tmp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = tmp;
}
}
}
puts("");
puts("Ascending order arrray: ");
for (int i = 0; i < DIM; i++) {
printf("%3d", arr[i]);
}
puts("");
}
`
In the second loop, j should be used instead of i
if (arr[j] > arr[j + 1]) {
tmp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = tmp;
}
Use j in the body of the second loop instead of i.`
// Bubble sort
for (int i = 0; i < DIM - 1; ++i) {
for (int j = 0; j < DIM - i - 1; ++j) {
// Compare two elements and swap if first > second
// Use of tmp variable (temporary)
if (arr[j] > arr[j + 1]) {
tmp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = tmp;
}
}
}
#include <stdio.h>
#define DIM 10
int main() {
int arr[DIM] = {1, 5, 6, 8, 7, 9, 3, 2, 4, 10};
int tmp;
puts("Original array: ");
for (int i = 0; i < DIM; i++) {
printf("%3d", arr[i]);
}
// Bubble sort
for (int i = 0; i < DIM - 1; ++i) {
for (int j = 0; j < DIM - i - 1; ++j) {
// Compare two elements and swap if first > second
// Use of tmp variable (temporary)
if (arr[j] > arr[j + 1]) {
tmp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = tmp;
}
}
}
puts("");
puts("Ascending order arrray: ");
for (int i = 0; i < DIM; i++) {
printf("%d", arr[i]);
}
puts("");
}
*Change: need to use "j" inplace of "i" in the 2nd for loop statements.

Something is wrong with my bubble sort output

This is just a normal bubble sort code, but something is wrong in it.
#include <stdio.h>
#include <stdlib.h>
void bubble_sort(int size, int *arr);
int main(void)
{
int *array, size;
printf("enter the amount of data: ");
scanf("%d", &size);
array = (int*)malloc(sizeof(int) * size);
for (int i = 0; i < size; ++i)
{
scanf("%d", &array[i]);
}
bubble_sort(size, array);
for (int i = 0; i <= size; ++i)
{
printf("%d ", array[i]);
}
printf("\n");
return 0;
}
void bubble_sort(int size, int *arr)
{
for (int i = 0; i < size; ++i)
{
for (int j = 0; j < size; ++j)
{
if (arr[j] > arr[j + 1])
{
int temp;
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
else if (arr[j] == arr[j + 1])
{
continue;
}
}
}
}
When I execute it, a zero appear in the output when it must be print 1 2 3
[my_username#my_computer bubble_sort]$ ./bubble_sort
enter the amount of data: 3
3 1 2
0 1 2 3
^
|
Where are this zero came from?
Well, it is not quite Bubble Sort.
To start, as pointed out in the comments: arr[j + 1] accesses the array with an invalid index - one past the end of the array when j is at its maximum value (size - 1).
The loop to print the array
for(int i = 0; i <= size; ++i)
has a similar off-by-one error. i < size is the desired condition.
Accessing an array out-of-bounds invokes Undefined Behaviour.
The else if block within the sort is superfluous.
The simplified variant of bubble sort is usually written as:
void bubble_sort(int *array, size_t length)
{
for (size_t i = 0; i < length; i++) {
for (size_t j = i + 1; j < length; j++) {
if (array[i] > array[j]) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
}
Whereas the standard bubble sort stops if it makes a pass on the array without swapping.
void bubble_sort(int *array, size_t length)
{
int swapped;
do {
swapped = 0;
for (size_t i = 1; i < length; i++) {
if (array[i - 1] > array[i]) {
int temp = array[i - 1];
array[i - 1] = array[i];
array[i] = temp;
swapped = 1;
}
}
} while (swapped);
}
This can be optimized by observing that all elements after the last swap have already been sorted.
void bubble_sort(int *array, size_t length)
{
do {
size_t n = 0;
for (size_t i = 1; i < length; i++) {
if (array[i - 1] > array[i]) {
int temp = array[i - 1];
array[i - 1] = array[i];
array[i] = temp;
n = i;
}
}
length = n;
} while (length);
}

unwanted element popping up in int list

I have written a C-program to generate random numbers and then sort them with the bubblesort-algorithm.
However, printing out the numbers (by an array, see the code) will show that the first element is 63, no matter what the randomly generated numbers were.
What causes this? And is there a more elegant way to bypass this than just skipping the first element of the list?
int list[10];
int cache_num;
srand((unsigned) (time(NULL))); //Gives the rand() function a new seed from the current time
for (int i = 0; i < 10; i++) {
list[i] = rand();
printf("\n%d", list[i]);
}
for (int i = 0; i < 10; i++) {
for (int j = 0; j < (10 - i); j++) {
if (list[j] > list[j + 1]) {
cache_num = list[j];
list[j] = list[j + 1];
list[j + 1] = cache_num;
}
}
}
for (int i = 0; i < 10; i++) {
printf("\n%d", list[i]);
}
In the inner loop of these loops
for (int i = 0; i < 10; i++) {
for (int j = 0; j < (10 - i); j++) {
if (list[j] > list[j + 1]) {
cache_num = list[j];
list[j] = list[j + 1];
list[j + 1] = cache_num;
}
}
}
there is an access to the non-existent element of the array with the index 10
list[j] = list[j + 1];
^^^^^^
when j is equal to 9.
It si better to write the loop like
for (int j = 1; j < (10 - i); j++) {
if (list[j - 1] > list[j]) {
cache_num = list[j];
list[j] = list[j - 1];
list[j - 1] = cache_num;
}
You are going one past the array when the variable j reaches the value of 9. Use (10 - i - 1) to resolve the issue:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void) {
int list[10];
int cache_num;
srand((unsigned) (time(NULL))); //Gives the rand() function a new seed from the current time
for (int i = 0; i < 10; i++) {
list[i] = rand();
printf("%d\n", list[i]);
}
for (int i = 0; i < 10; i++) {
for (int j = 0; j < (10 - i - 1); j++) { // note here ...
if (list[j] > list[j + 1]) {
cache_num = list[j];
list[j] = list[j + 1];
list[j + 1] = cache_num;
}
}
}
putchar('\n');
for (int i = 0; i < 10; i++) {
printf("%d\n", list[i]);
}
return 0;
}
Here in the following line you are going out of bounds because of which your are getting garbage value and thus altering your final result. Ex: when i=0 and j=9, this loops terminating condition will be is 9 < 10-0 which is true and it will execute. But for list [ j + 1 ] it will go out of bounds because there is no list [ 10 ].
for (int j = 0; j < (10 - i); j++){ ... }
It should have condition with -1 , (10-i-1)
for (int j = 0; j < (10 - i - 1); j++) { ... }
Instead of your implementation of the bubble sort to sort the data of 10 elements, you can use the below implementation.
The idea behind is that when you analyze (which you should) how the bubble-sort algorithm basically sorts the data, you will see a pattern i.e. in each pass of the inner-loop, the largest element (in-case of sorting the data in increasing order) will automatically go to its right location so, you don't need to consider that element again as it is already in its right position.
#include <stdio.h> // For basic I/O functions.
#include <stdlib.h> // For srand() & rand() functions.
#include <time.h> // For time(NULL) functions.
#define MAX_ARRAY_SIZE 10
int main(void) {
int list[10];
srand(time(NULL));
for(int i = 0; i < MAX_ARRAY_SIZE; ++i) {
list[i] = rand();
}
// Implementation of Bubble-Sort
for(int i = (MAX_ARRAY_SIZE - 1); i >=0; --i) {
bool is_sorted = true;
for(int j = 0; j < i; ++j) {
if(list[j] > list[j + 1]) {
int cache_num = list[j];
list[j] = list[j + 1];
list[j + 1] = cache_num;
is_sorted = false;
}
}
if(is_sorted) {
break;
}
}
for(int i = 0; i < MAX_ARRAY_SIZE; ++i) {
printf("%d ", list[i]);
}
printf("\n");
return 0;
}
P.S: As you are sorting only 10 elements, using bubble-sort is not going to make any difference, but I suggest you use insertion-sort instead of bubble-sort because insertion-sort is faster for small-size arrays.
Refer: Comparison Between Bubble-Sort/Selection-Sort/Insertion-Sort.
For Some Fun: Watch this bubble sort algorithm dance. 😁

In C: negative numbers insertion sort

I'm fairly new into programming and my teacher want me to implement insertion sort in C.
My code works, but not with negative numbers if I use it with negative numbers in my array I always get a segmentation fault:
void insertion_sort(int array[], int len) {
int i = 0;
int j = 1;
signed int tmp = array[0];
for(i = 1; i < len; i++) {
tmp = array[i];
j = i - 1;
if(j >= 0){
while(tmp < array[j]) {
array[j + 1] = array[j];
j = j - 1;
}
}
array[j + 1] = tmp;
}
}
Change this code snippet
if(j >= 0){
while(tmp < array[j]) {
array[j + 1] = array[j];
j = j - 1;
}
}
to
while ( j >= 0 && tmp < array[j] ) {
array[j + 1] = array[j];
j = j - 1;
}
Take into account that there is no sense to initialize defined variables
int i = 0;
int j = 1;
signed int tmp = array[0];
because they are overwritten in the followed statements.

Strange Bubble sort behaviour

Can anyone explain why this bubble sort function doesn't work and why I lose numbers in my output? I'm very new to C, so please forgive me if this is something very obvious I have missed.
#include <stdio.h>
#include <stdlib.h>
int bubble(int array[],int length) {
int i, j;
int temp;
for(i = 0; i < (length); ++i) {
for(j = 0; j < (length - 1); ++j) {
if(array[i] > array[i+1]) {
temp = array[i+1];
array[i+1] = array[i];
array[i] = temp;
}
}
}
return 0;
}
int main() {
int array[] = {12,234,3452,5643,0};
int i;
int length;
length = (sizeof(array)/sizeof(int));
printf("Size of array = %d\n", length);
bubble(array, length);
for (i = 0; i < (length); ++i) {
printf("%d\n", array[i]);
}
return 0;
}
Output
Size of array = 5
12
234
3452
0
0
In your inner loop, you don't use j at all. Double check your logic.
Also note that array[i+1] goes beyond the array boundary.
for (i = 0; i < (length-1); ++i) {
for (j = 0; j < (length-i-1); ++j) {
if(array[j] > array[j+1]) {
temp = array[j+1];
array[j+1] = array[j];
array[j] = temp;
}
}
}
In a bubble sort you only use the inner loop variable.
Another thing, the inner loop goes from 0 to i if I remember well; but I think that's just an optimisation (as the tail is remains sorted in each step).
Try to run step by step your code with paper and pencil. That always works.
for (i = 0; i < (length); i++) {
for (j = 1; j < (length-i); j++) {
if(array[j-1] > array[j]) {
temp = array[j-1];
array[j-1] = array[j];
array[j] = temp;
}
}
}

Resources