Insertion sort not printing all values in C - c

Insertion sort is not working, it is only printing some of the values. Does anyone know what I can do to fix it?
void insertion(int Array[], int n) {
for (int i = 1; i < n; i++) {
int j = i;
while (j >= 0 && Array[j] < Array[j - 1]) {
int temp = Array[j];
Array[j] = Array[j - 1];
Array[j - 1] = temp;
j--;
}
}
}

The test in the inner loop is incorrect: when j == 0 you read and possibly modify the element at offset -1, which has undefined behavior, possibly causing the incorrect output, but since you did not post the output code, there might be other problems there.
Here is a modified version:
void insertion(int Array[], int n) {
for (int i = 1; i < n; i++) {
for (int j = i; j > 0 && Array[j] < Array[j - 1]; j--) {
int temp = Array[j];
Array[j] = Array[j - 1];
Array[j - 1] = temp;
}
}
}

Insertion Sort: Idea
 Similar to how most people arrange a hand of poker cards
Start with one card in your hand
Pick the next card and insert it into its proper sorted order
Repeat previous step for all cards

Related

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);
}

Stack around Variable a is corrupted

#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]);
}
}

Find the index of maximum element in BST - C

I got an assignment - creating an array and finding the index of maximum element in the array.
I need to do it with Log(N) run-time so I made a binary tree function, which right know returns the value of maximum element.
I am trying to change to so it can return the index of the maximum element with no luck so far.
appreciate any kind of help.
the code is :
void max_value(int *a, int i, int n)
{
int j, temp;
temp = a[i];
j = 2 * i;
while (j <= n)
{
if (j < n && a[j + 1] > a[j])
j = j + 1;
if (temp > a[j])
break;
else if (temp <= a[j])
{
a[j / 2] = a[j];
j = 2 * j;
}
}
a[j / 2] = temp;
return;
}
int Array_Search(int *a, int n) {
int i;
for (i = n / 2; i >= 1; i--)
{
max_value(a, i, n);
}
return a[1];
}

Unsure why does Bubble sort code have a segmentation fault

Hi I'm using gdb to debug my bubble sort code but I don't get why it keeps breaking at if(a[j] < a[j-1]
here is my bubble sort function
void sort(int a[], int n) {
int i, j, nswaps, tmp;
for(i = 0; i < n; i++) {
nswaps = 0;
for(j = 0; j > i; j++) {
if(a[j] < a[j-1]) {
tmp = a[j];
a[j] = a[j-1];
a[j-1] = tmp;
nswaps++;
}
}
if(nswaps == 0) break;
}
}
Please do help me thanks!!
updated code: still has a segmentation fault
void sort(int a[], int n) {
int i, j, nswaps;
for (i = 0; i < n; i++) {
nswaps = 0;
for (j = 1; j > i; j++) {
if (a[j] < a[j-1]) {
int tmp;
tmp = a[j];
a[j] = a[j-1];
a[j-1] = tmp;
nswaps++;
}
}
if (nswaps == 0) break;
}
}
In the first iteration of the outer loop (when value of i is 0), the inner loop becomes an infinite loop, because value of j starts from 0 and keeps increasing. Eventually j becomes large enough for your program to access some unallocated memory, hence causing a segmentation fault.
Also, in the first iteration of the inner loop, value of j is 0, so a[j - 1] will try to access a memory location out of bound for your program.
j > i is false on the first iteration, so if(nswaps == 0) is true and the loops break, no sorting occurs.
Instead of iterating the outside loop n times, iterate n-1 times.
No need to count swaps, a simply boolean is sufficient.
After the first inner loop iteration, the lowest element of the array is found and in place at the end. The next inner loop only needs to iterate to next-last element, etc.
size_t is the Goldilocks type for array indexing, neither too narrow, nor too wide. Better than using int for indexing. Remember that is is an_unsigned type_.
No need to declare a variable until needed.
#include <stdbool.h>
#include <stdlib.h>
void bubble_sort(int a[], size_t n) {
while (n > 1) {
bool swapped = false;
for (size_t j = 1; j < n; j++) {
if (a[j-1] < a[j]) {
int tmp = a[j];
a[j] = a[j - 1];
a[j - 1] = tmp;
swapped = true;
}
}
if (!swapped) {
break;
}
n--;
}
}

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.

Resources