Bubble sort in C: Function not changing array data - c

Code:
#include <stdio.h>
void testSort(int values[], int n);
int main(void)
{
int hs[] = {5,3,2,1,4};
printf("Unsorted: %i %i %i %i %i\n", hs[0], hs[1], hs[2], hs[3], hs[4]);
testSort(hs, 5);
printf("Sorted: %i %i %i %i %i\n", hs[0], hs[1], hs[2], hs[3], hs[4]);
}
void testSort(int values[], int n)
{
for (int i = 0; i < n-1; i++)
{
int hold;
int current = values[i];
int next = values[i + 1];
if (current > next)
{
hold = current;
current = next;
next = hold;
}
}
return;
}
I'm trying to do bubble sort and right now it goes through the array once, but my question is: Why isn't my hs[] updating after calling function? The second printf shows that it remained the same.
EDIT:
As mentioned, turns out I was changing data but of the copies. For some reason I when I created the variables current/next I felt as if they were representing values[i]/values[i+1] but in reality I was just creating new variable and passing the value of values[0] which is 5 and assigning it to current. Obviously leaving values[] unchanged. Thanks everyone

The problem is that you're only modifying the function's local variables, not the array's elements.
It's the same principle as why this program will print 1 and not 2:
int main()
{
int array[] = {1};
int x = array[0];
x = 2;
printf("array[0] = %d\n", array[0]);
return 0;
}
You need to assign values to the array's elements:
void testSort(int values[], int n)
{
for (int i = 0; i < n-1; i++)
{
if (values[i] > values[i+1])
{
int hold = values[i];
values[i] = values[i+1];
values[i+1] = hold;
}
}
}
Once you've fixed this, you will notice that this function only works for some inputs.
Solving that bug is left as an exercise.

Please try below code:-
void bubble_sort(int list[], int n){
int c, d, t;
for (c = 0 ; c < ( n - 1 ); c++)
{
for (d = 0 ; d < n - c - 1; d++)
{
if (list[d] > list[d+1])
{
t = list[d];
list[d] = list[d+1];
list[d+1] = t;
}
}
}
}

Related

Return multiple values from function prototype in C. Results are multiple products

So I have a function prototype find all products from two numbers whether it has 2 or 3 digits. I believe that function can only return one value. So how do I print out all possible values in main using printf statement?
int find_largest_products(int ndigits){
int min = 1;
int max;
int smallest_num;
int largest_num = 0;
int product = 0;
int max_min_product = 0;
//Finding the minima. 1 digit = 1; 2 digits = 10; 3 digits = 100
smallest_num = min * pow(10, ndigits-1);
//Finding the maxima. 1 digits = 9; 2 digits = 99; 3 digits = 999
for (int i = 0; i < ndigits; i++){
max = 9 * pow(10, i);
largest_num += max;
}
for (int x = largest_num; x >= smallest_num; x--){
for (int y = smallest_num; y <= largest_num; y++){
product = x * y;
max_min_product = product;
}
}
return max_min_product;
}
int main() {
int num = find_largest_palindrome(2);
printf("Results: %d\n", num);
return 0;
}
Callback function:
int find_largest_products(int ndigits, int (*callback)(int, void *), void *baton){
//...
//max_min_product = product;
int r= callback(product, baton);
if (r) return r;
//...
return 0;
}
int print_product(int product, void *ignored) {
printf(" %d", product);
return 0;
}
int main()
{
//...
printf("Results:");
find_largest_products(2, print_product, NULL); // Invocation is here
printf("\n");
//...
}
What about commas? What about newline every so many? We can adapt the callback.
int print_product(int product, void *baton) {
int *counter = baton;
if (counter % 8 == 7) {
printf(", %d\n", product);
else if (counter % 8 == 0)
printf("%d\n", product);
else
printf(", %d\n", product);
++*counter;
return 0;
}
But now the invocation should look like:
int counter = 0;
find_largest_products(2, print_product, &counter); // Invocation is here
Notice how this keeps state between invocations. Here it's an int, but it could easily be a struct or a pointer thereof to enable keeping arbitrary amounts of state.
So this is the pattern of a callback function that can do whatever it wants. The callback function takes the accumulating argument found by find_largest_products and the state argument baton from find_largest_products, and returns 0 to continue or nonzero to bail. Here the callback function only prints the value out and never fails. I also consider this lower-skill-level than dynamic memory. We only need to learn the somewhat annoying syntax for function pointers and the rest easy concepts. Note that we don't take the address of a function pointer with &; it's like an array in that regard.
To make the point this is the general form; here's the callback that could be passed to retrieve the list.
struct product_info {
int *products;
int nproducts;
int aproducts;
};
int gather_products(int product, void *baton)
{
struct product_info *info = baton;
// normal dynamic stretchy array zzzzz
if (info->nproducts == info->aproducts) {
if (info->aproducts == 0) {
info->products = malloc(sizeof(int)*4);
if (!info->products) return 1;
info->aproducts = 0;
} else {
void *more = realloc(sizeof(int) * (info->aproducts << 1));
if (!more) return 1;
info->aproducts <<= 1;
info->products = more;
}
}
// end stretchy array
info->products[info->nproducts++] = product;
return 0;
}
int main()
{
//...
printf("Results: ");
struct product_info info = { NULL, 0, 0 };
if (find_largest_products(2, gather_products, &info)) { // Invocation is here
fprintf(stderr, "Out of memory\n");
free(info->products);
}
for (int i = 0; i < info->nproducts; i++)
printf("%s%d", (i == 0) ? "" : ", ", info->products[i]);
free(info->products);
printf("\n");
//...
}
Returning the list requires dynamic memory. It's interesting to note that function pointers provides a separation of concerns that I've come to appreciate in these late days; we can separate the generating algorithm from the storing of the results.
Another sample: find biggest!
int biggest_product(int product, void *baton) {
int *biggest = baton;
if (*biggest < product) *biggest = product;
return 0;
}
int main()
{
int biggest = 0;
find_largest_products(2, biggest_product, &biggest); // Invocation is here
printf("Biggest product is: %d\n", biggest);
}
Notice how easy it is to swap what you do with the products as you generate them.

Optimization of program processing structured input for large data

I have this one task. To make it more clear, I am gonna use picture below as an example. Input and output is separated with dotted line. First line of input is number N - number of sets. For every set, it's first line are 2 numbers - first one declares how many numbers am I gonna process and second one is number of intervals. Second line specifies the numbers to process and third line contains 2 numbers X and Y, which create and interval. For every interval I have to output 3 numbers - lowest number on interval, index of highest number on interval and XOR of all numbers. Everything is running fine except it is really slow for big data and I have no idea how to make work faster. I have attached my code and large data input as well.
input.txt
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int id;
int index;
} Censor;
int Xor(const int x, const int y, const Censor array[]) {
int xor = array[x].id;
if (x == y) {
return xor;
}
for (int i = x + 1; i <= y; i++) {
xor ^= array[i].id;
}
return xor;
}
int int_cmp(const void *a, const void *b) {
const Censor *ia = (const Censor *)a;
const Censor *ib = (const Censor *)b;
return (ia->id - ib->id);
}
int LowestId(const int x, const int y, Censor array[]) {
int id = array[x].id;
if (x == y) {
return id;
}
qsort(array, y - x + 1, sizeof(Censor), int_cmp);
return array[0].id;
}
int HighestIdIndex(const int x, const int y, Censor array[]) {
int index = array[x].index;
if (x == y) {
return index;
}
qsort(array, y - x + 1, sizeof(Censor), int_cmp);
return array[y].index;
}
int main() {
int t, n, q, b, e;
int max = 100;
int count = 0;
int *output = (int *)malloc(max * sizeof(output));
scanf("%d", &t); //number of sets
for (int i = 0; i < t; i++) {
scanf("%d %d", &n, &q);
//I am making 3 separate arrays for numbers, because some of them are being sorted and some of them not
Censor lowest_id[n];
Censor highest_id_index[n];
Censor xor[n];
//This loop fills arrays with the numbers to be processed
for (int j = 0; j < n; j++) {
scanf("%d", &(lowest_id[j].id));
lowest_id[j].index = j;
highest_id_index[j].id = lowest_id[j].id;
highest_id_index[j].index = j;
xor[j].id = lowest_id[j].id;
xor[j].index = j;
}
// Now I am scanning intervals and creating output. Output is being stored in one dynamically allocated array.
for (int k = 0; k < q; k++) {
scanf("%d %d", &b, &e);
if (count + 3 >= max) {
max *=2;
int *tmp = (int *)realloc(output, max * sizeof(tmp));
if (tmp == NULL) {
return 1;
} else {
output = tmp;
}
}
output[count++] = LowestId(b, e, lowest_id);
output[count++] = HighestIdIndex(b, e, highest_id_index);
output[count++] = Xor(b, e, xor);
}
}
printf("---------------------\n");
for (int i = 0; i < count; i++) {
printf("%d\n", output[i]);
}
free(output);
return 0;
}
Thanks #Dan MaĊĦek and #Alex Lop. Sorting subarray in this case was unnecessary. Much easier is to iterate through the subarray in linear complexity.

assigned value to dynamic array created in void function doesnt return the same value in main()

I have a problem with dynamic arrays in C. My program was working perfectly, but I was asked to put the creation of dynamic array into a seperate void. I did it, and it still worked great, but then I had to assign a value to a certain point of the created array in void, and make it return the said value, however, what I get is a random value. The function works by sending a pointer and the lenght of required array into void, and then makes the pointer into a dynamic array.
#include <stdio.h>
#include <stdlib.h>
#define MAX 255
void ieskom (int skaiciai[],int n, int *de, int *me, int *n1, int *n2)
{
int i = 0;
int j = 0;
int nr1 = 0;
int nr2 = 0;
int temp = 0;
int temp1 = 0;
int eile = 0;
int eile1 = 0;
int *did;
did = (int*)calloc(n,sizeof(int));
if (did==NULL)
{
printf("Nepriskirta atminties.");
exit(0);
}
int *maz;
maz = (int*)calloc(n,sizeof(int));
if (maz==NULL)
{
printf("Nepriskirta atminties.");
exit(0);
}
i = 0;
for (i = 0; i < n; i++)
{
if (skaiciai[i] < skaiciai[i+1])
{
did[j] = did[j] + 1;
if (did[j] > temp)
{
eile = j;
temp = did[j];
nr1 = i+1;
}
}
else
{
did[j] = did[j] + 1;
if (did[j] > temp)
{
eile = j;
temp = did[j];
nr1 = i+1;
}
j = j + 1;
}
}
j = 0;
for (i = 0; i < n; i++)
{
if (skaiciai[i] > skaiciai[i+1])
{
maz[j] = maz[j] + 1;
if (maz[j] > temp1)
{
eile1 = j;
temp1 = maz[j];
nr2 = i+1;
}
}
else
{
maz[j] = maz[j] + 1;
if (maz[j] > temp1)
{
eile1 = j;
temp1 = maz[j];
nr2 = i+1;
}
j = j + 1;
}
}
*de = did[eile];
*me = maz[eile1];
*n1 = nr1;
*n2 = nr2;
free(did);
free(maz);
}
/*int masyvas(x)
{
int y;
y = (int*)malloc(x*sizeof(int));
return y;
}*/
void *masyvas (int *skaiciai, int n)
{
*skaiciai = (int*)malloc(n*sizeof(int));
skaiciai[2] = 5;
return skaiciai;
}
int main()
{
int n1 = 0;
int n2 = 0;
int de = 0;
int me = 0;
int i = 0;
int n = 0;
int *skaiciai;
scanf("%d", &n);
// skaiciai = masyvas(n); // naudojant int
masyvas(&skaiciai, n);
printf("2 = %d", skaiciai[2]);
if (skaiciai==NULL)
{
printf("Nepriskirta atminties.");
exit(0);
}
for (;i < n; i++)
{
scanf("%d", &skaiciai[i]);
}
ieskom (skaiciai, n, &de, &me, &n1, &n2);
if (de > me)
{
printf("Elementu numeriai:");
printf(" %d", n1-de+1);
printf(" %d\n", n1);
printf("\nAtstumas tarp ju: %d", de-2);
}
else
{
printf("Elementu numeriai:");
printf(" %d", n2-me+1);
printf(" %d\n", n2);
printf("\nAtstumas tarp ju: %d", me-2);
}
free(skaiciai);
getchar();
getchar();
return 0;
}
The problem is in void masyvas and printf skaicia[2] - I assign a certain value to skaiciai[2], yet it prints a random one. How do I fix it?
EDIT: Thank you for your answers and explanations, it really helped me a lot! I know have solved my problem, and most importantly, I know why it was a problem in the first place.
First of all, you should translate variables and texts to english (your code lack of comments, this should apply to them too).
Next your masyvas() function returns a pointer to the allocated array (why void* ?!) but when you call it you don't get the returned value.
You have to choose: either you pass a pointer to your function (an array is a pointer, to if you want an array to be allocated from a function you have to pass a pointer to the pointer, so a int **), or you use the returned value.
Allocating with returned value:
// this function allocates a int* tab of size n and set one value
int *allocate_tab(int n) {
int *tmp;
tmp = malloc(n*sizeof(int));
if (tmp == NULL) {
return(NULL); // failed
}
tmp[2] = 5;
return(tmp);
}
// in main (or other function)
int *mytab;
mytab = alloc_tab(45);
Allocating by passing a pointer to the array:
void alloc_tab(int **tab, int n) {
*tab = malloc(n*sizeof(int));
if (*tab == NULL) {
return;
}
(*tab)[2] = 5;
}
// in main (or other)
int *mytab;
alloc_tab(&mytab, 45);
If you can't understand this stuff I guess you should read more about memory, allocation and pointers.
You need to pass a pointer-to-pointer here and do not need to return anything.
void masyvas (int **skaiciai, int n)
{
*skaiciai = (int*)malloc(n*sizeof(int));
(*skaiciai)[2] = 5;
}
When you declare int *skaiciai, the variable is a pointer to type int. skaiciai holds the address that points to an int. When you pass &skaiciai, you're passing the address of the address that points to an int. So because this is an address of an address, its a double pointer.

Manipulating a global array in a recursive function

I'm working through an algorithms MOOC and have a small program that takes an array A of ints in arbitrary order, counts the number of inversions (an inversion being the number of pairs (i,j) of array indices with i<j and A[i] > A[j]).
Below is the code I've written. I'm trying to tackle it using a "divide and conquer" approach where we recursively split the input array into two halves, sort each half individually while counting the inversions and then merge the two halves.
The trick is I need to keep track of the number of inversions and sort the arrays, so I pass the original array around the various recursive calls as an argument to the function and pass the count of inversions as a return value.
The code executes correctly through the first set of recursive calls that successively divide and sort [1,5,3], however when I get to the 3rd invocation of mergeAndCountSplitInv it crashes at the line:
sortedArrayLeft = realloc(sortedArrayLeft, sizeof(int)*(rightLen + leftLen));
with the error:
malloc: *** error for object 0x100103abc: pointer being realloc'd was not allocated
I can't see where I'm not using malloc correctly and I've combed through this checking to see I'm doing the pointer arithmetic correctly and can't spot any errors, but clearly error(s) exist.
Any help is appreciated.
// main.c
// inversionInC
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
// function to help with debugging array/pointer arithmetic
void logArrayLenAndContents (char *arrayName, int arrayToPrint[], int arrayLen){
printf("%s\n", arrayName);
printf("len:%d\n", arrayLen);
for (int idx = 0; idx < arrayLen; idx++) {
printf("array[%d]: %d\n", idx, arrayToPrint[idx]);
}
}
int mergeAndCountSplitInv(int sortedArrayLeft[], int leftLen, int sortedArrayRight[], int rightLen)
{
printf("Calling mergeAndCount with sortedArrayLeft:\n");
logArrayLenAndContents("left Array", sortedArrayLeft, leftLen);
printf("...and sortedArrayRight:\n");
logArrayLenAndContents("right Array", sortedArrayRight, rightLen);
int i = 0;
int j = 0;
int k = 0;
int v = 0; // num of split inversions
int* outArray;
outArray = malloc((leftLen + rightLen) * sizeof(int));
while (i < leftLen && j < rightLen) {
if (sortedArrayLeft[i] < sortedArrayRight[j]) {
outArray[k] = sortedArrayLeft[i];
i++;
} else{
outArray[k] = sortedArrayRight[j];
v += leftLen - i;
j++;
}
k++;
}
// if at the end of either array then append the remaining elements
if (i < leftLen) {
while (i < leftLen) {
outArray[k] = sortedArrayLeft[i];
i++;
k++;
}
}
if (j < rightLen) {
while (j < rightLen) {
outArray[k] = sortedArrayRight[j];
j++;
k++;
}
}
printf("Wrapping up mergeAndCount where outArray contains:\n");
logArrayLenAndContents("outArray", outArray, k);
sortedArrayLeft = realloc(sortedArrayLeft, sizeof(int)*(rightLen + leftLen));
return v;
}
int sortAndCount(int inArray[], int inLen){
printf("Calling sortAndCount with:\n");
logArrayLenAndContents("inArray", inArray, inLen);
if (inLen < 2) {
return 0;
}
int inArrayLenPart1 = ceil(inLen/2.0);
int inArrayLenPart2 = inLen - inArrayLenPart1;
int* rightArray = malloc(sizeof(int) * inArrayLenPart2);
rightArray = &inArray[inArrayLenPart1];
int x = sortAndCount(inArray, inArrayLenPart1);
printf("sortAndCount returned x = %d\n\n", x);
int y = sortAndCount(rightArray, inArrayLenPart2);
printf("sortAndCount returned y = %d\n\n", y);
int z = mergeAndCountSplitInv(inArray, inArrayLenPart1, rightArray, inArrayLenPart2);
printf("mergeAndCount returned z = %d\n", z);
return x+y+z;
}
int main(int argc, const char * argv[])
{
static int* testArray;
testArray = malloc(5 * sizeof(int));
for (int i = 0; i<=4; i++) {
testArray[0] = 1;
testArray[1] = 5;
testArray[2] = 3;
testArray[3] = 2;
testArray[4] = 4;
}
int x = sortAndCount(testArray, 5);
printf("x = %d\n", x);
return 0;
}
This happens because the value of sortedArrayLeft gets lost as soon as the function returns. The realocated value does not make it to the caller, so inArray of the sortAndCount may be pointing to freed memory if realloc needs to reallocate and copy.
In order to fix this, pass a pointer to the pointer, letting sortedArrayLeft to propagate back to inArray of sortAndCount:
int mergeAndCountSplitInv(int **sortedArrayLeft, int leftLen, int sortedArrayRight[], int rightLen) {
...
*sortedArrayLeft = realloc(*sortedArrayLeft, sizeof(int)*(rightLen + leftLen));
return v;
}
...
int sortAndCount(int **inArray, int inLen) {
...
int z = mergeAndCountSplitInv(inArray, inArrayLenPart1, rightArray, inArrayLenPart2);
}
...
int x = sortAndCount(&testArray, 5);

Incorrect size of array

#include <stdio.h>
void Heapify(int num[], int start, int end)
{
int root = start;
while(root*2+1<=end)
{ // at least one child exists
int swap = root;
int lchild = root*2+1;
int rchild = root*2+2;
if(num[swap]<num[lchild]){
swap = lchild;
}
if(rchild<=end && num[swap]<num[rchild]){
swap = rchild;
}
if(swap!=root){
// swap here
int temp = num[root];
num[root] = num[swap];
num[swap] = temp;
root = swap;
}
else
return;
}
}
void buildHeap(int num[]) {
int length=sizeof(num)/sizeof(num[0]);
int start = (length/2)-1; // Starting from last parent
int end = length-1;
while(start>=0){
Heapify(num,start, end);
if(start==0)
break;
start= start-1;
}
}
void heapsort(int num[]) {
int length=sizeof(num)/sizeof(num[0]);
printf("length = %d ", length); // length = 1 (Wrong)
buildHeap(num);
int i;
//for (i = 0; i < length; i++)
//printf("%d ",num[i]);
int end = length-1;
while(end>0){
// swap first elem with last
int temp = num[0];
num[0] = num[end];
num[end] = temp;
Heapify(num,0,end-1);
end--;
}
}
int main() {
int num[]={1,7,-32,4,101,-99,16,3};
heapsort(num);
return 0;
}
http://codepad.org/zcfNOtye
When I print it in main, the length is showing correct but inside the function(heap sort), its showing wrong. I can't find any mistakes in passing the array. What am I missing?
Arrays decay to pointers when passed as parameters, you need to pass the length of the array as a separate parameter.
I.e.: you can't find the length of the array like this.
void buildHeap(int num[]) {
int length=sizeof(num)/sizeof(num[0]);
}
sizeof(num) will return sizeof(int*).

Resources