I am trying to create this program that takes an int number from the user then randomizes a pair of numbers, based on the input, inside the an array of struct. Then it sorts this array based on the sum of the number pair the program randomized.
However my program won´t sort the array of struct. It doesn´t do the sorting properly and Im not sure why. Here is the code.
#define MAX 10
struct NumPair{
int n,m;
};
int main()
{
int i, j, amount=0;
NumPair NumPair[MAX];
srand(time(NULL));
printf("How many pair of numbers? (max 10): ");
scanf("%d", &amount);
for (i=0; i<amount; i++)
{
NumPair[i].n = rand() % 11;
NumPair[i].m = rand() % 11;
}
for (i=0; i<amount; i++)
{
for(j=1; j<amount; j++)
{
if( (NumPair[i].n+NumPair[i].m) > (NumPair[j].n+NumPair[j].m) )
{
int tmp;
tmp = NumPair[i].n;
NumPair[i].n = NumPair[j].n;
NumPair[j].n = tmp;
tmp = NumPair[i].m;
NumPair[i].m = NumPair[j].m;
NumPair[j].m = tmp;
}
}
}
for (i=0; i<amount; i++)
{
printf(" NumPair %d: (%d,%d)\n", i+1, NumPair[i].n, NumPair[i].m);
}
return 0;
}
What am I missing? It's probably something very silly.
Thanks in advance.
Your algorithm is incorrect. This little snippet:
for (i=0; i<amount; i++) {
for(j=1; j<amount; j++) {
will result in situations where i is greater than j and then you comparison/swap operation is faulty (it swaps if the i element is greater than the j one which, if i > j, is the wrong comparison).
I should mention that (unless this is homework or some other education) C has a perfectly adequate qsort() function that will do the heavy lifting for you. You'd be well advised to learn that.
If it is homework/education, I think I've given you enough to nut it out. You should find the particular algorithm you're trying to implement and revisit your code for it.
You are comparing iterators i with j. Bubble sort should compare jth iterator with the next one
for (i=0; i<amount; i++) //pseudo code
{
for(j=0; j<amount-1; j++)
{
if( NumPair[j] > NumPair[j+1] ) //compare your elements
{
//swap
}
}
}
Note that the second loop will go only until amount-1 since you don't want to step out of bounds of the array.
change to
for (i=0; i<amount-1; i++){
for(j=i+1; j<amount; j++){
Related
I am trying to sort an array of structs (A SJF Scheduler). I am using the qsort library function to sort the structs in increasing order according to the attribute bursttime. However, the output is not correct. I've checked some SO questions about the same but they served no use.
struct job
{
int jobno;
int bursttime;
};
typedef struct job job_t;
int mycompare(const void* first, const void* second)
{
int fb = ((job_t*)first)->bursttime;
int sb = ((job_t*)second)->bursttime;
return (fb - sb);
}
int main()
{
int n;
printf("Enter number of jobs: ");
scanf("%d", &n);
job_t* arr = (job_t*)malloc(sizeof(job_t) * n);
for(int i = 1; i <= n; ++i)
{
printf("Enter Burst time for Job#%d: ",i);
scanf("%d", &(arr[i].bursttime));
arr[i].jobno = i;
}
printf("\n");
printf("Order of the Jobs before sort:\n");
for(int i = 1; i <= n; ++i)
{
printf("%d\t", arr[i].jobno);
}
qsort(arr, n, sizeof(job_t), mycompare);
printf("\n");
printf("Order of the Jobs after sort:\n");
for(int i = 1; i <= n; ++i)
{
printf("%d\t", arr[i].jobno);
}
printf("\n");
printf("\n");
return 0;
}
This is my inputfile:
4
7
2
9
4
The output I'm getting is:
Order of the Jobs before sort:
1 2 3 4
Order of the Jobs after sort:
2 1 3 4
The expected order should be: 2,4,1,3. Am I missing anything?
At least this problem
for(int i = 1; i <= n; ++i) // bad
Use zero base indexing.
for(int i = 0; i < n; ++i)
You could change the indexing scheme to start from zero, as others have suggested, and this would certainly be the idiomatic way to do it.
But if you want to use 1-based indexing, you'll need to allocate an extra place in the array (position 0 that will never be used):
job_t* arr = (job_t*)malloc(sizeof(job_t) * (n + 1));
Then you'll need to start your sort at position 1 in the array:
qsort(&arr[1], n, sizeof(job_t), mycompare);
And, of course, you'll have to write your code to index from 1 -- but you've already done that.
The problem is that so many standard functions in C use zero-based indexing that doing anything else is inexpressive. That's a bigger problem than wasting one array position. But, for better or worse, I've had to convert to C a load of code from Fortran, so I've gotten used to working both ways.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I want to sort 12 integers using a "reverse bubble sort" (We call it "the drowning axe sort", whatever). My function looks good to me but something goes wrong.
Error: having typed my 12 random numbers I don't get the result printed, instead my compiler stops and does not proceed any further.
Can anyone help?
Code:
#include<math.h>
#include<math.h>
void array_clean(int a[11]) //just an array cleaner
{
for(int i=0; i<12; i++)
{
a[i] = a[i]&&0; // smth && 0 = 0 anyway
}
}
void axe_sort(int a[11]) //drowning-axe sort function
{
int place = 0;
for(int i=0; i<12; i++)
{
for(int j=0; j<12; j++)
{
if(a[j]<a[j+1])
place=a[j];
a[j] = a[j+1];
a[j+1] = place;
}
}
}
int main(void)
{
int array[11]; //declaring an integer array;
array_clean(& array[11]); // giving user-filed array to a cleaner function
printf("Enter 12 random integers you'd like to sort: ");
for(int m=0; m<12; m++)
{
scanf("%d", &array[m]); //letting user to fill an array
}
axe_sort(&array[11]); //sorting an array via our axe_sort function
for(int m=0; m<12; m++)
{
printf("%d", array[m]); //printing the sorted array
}
return 0;
}
Your array int array[11]; isn't doing what you think it is. That declares an array of 11 ints, indexed from 0 to 10 inclusive. There is no array[11] therefore trying to access this will lead to undefined behavior.
You've got the correct form of your for loop, it'll correctly iterate over 12 members of the array, numbered 0 to 11 inclusive. However you need to declare the array as int array[12]; to get it big enough to work.
Also, you're passing the array to the two functions using &array[11]. You just need to say array and it'll pass in the array correctly. What you're doing will cause the two functions to write over random memory, which definitely won't help.
Try fixing these and see what changes.
First of all, You should include stdio.h header file in order to use printf() and scanf()
You are dealing with 12 integers. Then Why did you declare an array of 11 integers???
int array[11]; //declaring an integer array; <-------- change the size to 12 from 11
The purpose of the array_clean(); is to initialize each number with 0. You can simply put 0 instead of a[i]&&0;
Here you are passing the address of 12th element.
array_clean(&array[11]); //<---------------------
You should pass the address of the base element(1st).
You can do this by two ways.
array_clean(&array[0]);
Or,
array_clean(array);
When an array is used as a value, its name represents the address of the first element.
And finally, please check your bubble sort logic.
for(int j=0; j<12; j++)
{
if(a[j]<a[j+1])
{place=a[j]; //<-----curly braces missing in the body of if
a[j] = a[j+1]; //<----error
a[j+1] = place;
}
}
For j=11, your code will try to access 12th index and that will give you a segmentation fault. Enclose the body of if with curly braces.
Here is the modified code
#include<math.h>
#include<stdio.h> // <---------- include this header file
void array_clean(int a[12]) //just an array cleaner
{
for(int i=0; i<12; i++)
{
a[i] = 0; // smth && 0 = 0 anyway
}
}
void axe_sort(int a[12]) //drowning-axe sort function
{
int i,j;
for(i=0; i<11; i++)
{
for(j=0; j<11-i; j++) //<-------- see the logic carefully
{
if(a[j] < a[j+1]) //<-----put curly braces
{int place=a[j];
a[j] = a[j+1];
a[j+1] = place;}
}
}
}
int main(void)
{
int array[12]; //declaring an integer array;
array_clean(&array[0]); // <---------------- pass the base address
printf("Enter 12 random integers you'd like to sort: ");
for(int m=0; m<12; m++)
{
scanf("%d", &array[m]); //letting user to fill an array
}
axe_sort(&array[0]); // <---------------- pass the base address
for(int m=0; m<12; m++)
{
printf("%d ", array[m]); //printing the sorted array
}
return 0;
}
I think you forgot to include the stdio.h library in your code
I am trying to implement Insertion sort algorithm in C.
But all I get is SIGSEGV error in online IDEs and the output doesn't show up in Code::Blocks. How to avoid Such errors.
#include <stdio.h>
#include <stdlib.h>
int main()
{
/* Here i and j are for loop counters, temp for swapping
count for total number of elements,array for elements*/
int i, j, temp, count;
printf("How many numbers are you going to enter");
scanf("%d", &count);
int n[20];
printf("Enter %d elements", count);
// storing elements in the array
for(i = 0; i < count; i++) {
scanf("%d", n[i]);
}
// Implementation of insertion sort algorithm
for(i = 0; i < count; i++) {
temp = n[i];
j = i - 1;
while(temp < n[j]) {
n[j+1] = n[j];
j = j - 1;
}
n[j+1] = temp;
}
printf("Order of sorted elements");
for(i = 0; i < count; i++) {
printf("%d", n[i]);
}
return 0;
}
There are a couple of problems with your code. First of all, what is a SIGSEGV error? Well, it's another name for the good old Segmentation fault error, which is basically the error you get when accessing invalid memory (that is, memory you are not allowed to access).
tl;dr: change scanf("%d",n[i]); to scanf("%d",&n[i]);. You're trying to read the initial values with scanf("%d",n[i]);, this raises a segmentation fault error because scanf expects addresses in which put the values read, but what you're really doing is passing the value of n[i] as if it were an address (which it's not, because, as you did not set any value for it yet, it's pretty much just memory garbage). More on that here.
tl;dr: change int n[20]; to int n[count]. Your array declaration int n[20]; is going to store at most 20 integers, what happens if someone wants to insert 21 or more values? Your program reserved a certain stack (memory) space, if you exceed that space, then you're going to stumble upon another program's space and the police (kernel) will arrest you (segmentation fault). Hint: try inserting 21 and then 100 values and see what happens.
tl;dr: change for(i = 0; i < count; i++) { to for(i = 1; i <= count; i++) {. This one is a logic problem with your indexes, you are starting at i = 0 and going until i = count - 1 which would be correct in most array iteration cases, but as j assumes values of indexes before i, you need i to start from 1 (so j is 0, otherwise j = -1 in the first iteration (not a valid index)).
My final code is as follows. Hope it helped, happy coding!
#include <stdio.h>
#include <stdlib.h>
int main() {
/*Here i and j are for loop counters,temp for swapping
count for total number of elements,array for elements*/
int i, j, temp, count;
printf("How many numbers are you going to enter?\n");
scanf("%d",&count);
int n[count];
printf("Enter %d elements\n",count);
//storing elements in the array
for(i = 0; i < count; i++) {
scanf("%d", &n[i]);
}
//Implementation of insertion sort algorithm
for(i = 1; i <= count; i++) {
temp = n[i];
j = i-1;
while(temp < n[j]) {
n[j+1] = n[j];
j--;
}
n[j+1] = temp;
}
printf("Order of sorted elements\n");
for(i = 0; i < count; i++) {
printf("%d\n",n[i]);
}
return 0;
}
Edit: If you're having trouble with online IDEs, consider running your programs locally, it saves a lot of time, plus: you never know what kernel version or magic the online IDEs are using to run your code (trust me, when you're coding in C -- fairly low level language, these things make a difference sometimes). I like to go all root style using Vim as text editor and gcc for compiling as well as gdb for debugging.
I am currently working on a simple code to store and display top-right triangular matrix. Well, everything was fine till I tried to input 4x4 matrix structure and gave the input. The first array of structure's (called a) last value changed although I did not put any code to change ANY of the values in a. It happens in the mReorder() function. Then I tried some try-and-errors find out the problem in the 3rd row of mReorder() function. I wonder why and how to solve it.
Here is my complete code:
#include<stdio.h>
//CMO fashion
typedef struct
{
int row;
int col;
int val;
}term;
#define MAX_TERMS 10
term a[MAX_TERMS], b[MAX_TERMS];
void mReorder(void);
int main()
{
int n, i, j;
printf("Enter the number of rows: ");
scanf("%d", &n);
if (n<1 || n>MAX_TERMS)
{
printf("\nInvalid number of rows!!");
exit(0);
}
i=nCount(n);
mRead(n,i);
for (j=0; j<i+1; j++) printf("\n%d\t%d\t%d", a[j].col, a[j].row, a[j].val);
mReorder();
for (j=0; j<i+1; j++) printf("\n%d\t%d\t%d", a[j].col, a[j].row, a[j].val);
printf("\n");
for (j=0; j<i+1; j++) printf("\n%d\t%d\t%d", b[j].col, b[j].row, b[j].val);
mDisplay();
return 0;
}
void mReorder(void)
{
int i, j, k, m=1;
b[0].col=a[0].col;
b[0].row=a[0].row;
b[0].val=a[0].val;
for(i=0; i<a[0].col; i++)
for (j=1; j<=a[0].val; j++)
if (a[j].row==i)
{
b[m].col=a[j].col;
b[m].row=a[j].row;
b[m].val=a[j].val;
m++;
}
}
void mDisplay(void)
{
int i, j, k, m=1;
printf("\nThe resulting matrix is:\n");
for (i=0; i<b[0].col; i++)
{
//printf("\na");
for (k=0; k<i; k++) printf("%5c", '-');
for (j=i; j<b[0].col; j++)
{
printf("%5d", b[m].val);
m++;
}
printf("\n");
}
}
void mRead(int n, int x)
{
int i, j, m=1, val;
printf("\nEnter %d elements of the matrix: \n", x);
a[0].row=a[0].col=n;
a[0].val=x;
for (i=0; i<n; i++)
{
for (j=0; j<=i; j++)
{
scanf("%d", &val);
a[m].row=j;
a[m].col=i;
a[m].val=val;
m++;
}
}
}
int nCount(int n)
{
if (n==1)
return 1;
return (n+nCount(n-1));
}
Can you explain what's going on here?
You allocate enough space for 10 term items, but nCount(4) returns 10, and nCount(5) returns 15, etc. If you specify a value bigger than 4, you overflow your array boundaries, leading to undefined behaviour — which is something to be avoided at all costs. In practice, one of your two arrays tramples over the other, but what happens when you access the other array out of bounds is entirely up to the compiler. It may appear to work; it may crash horribly; it may corrupt other data structures.
Nominally, since you allocate 10 elements in the arrays a and b, you should be OK with the 4x4 data, but in mRead(), you set m = 1 to start with, so you end up writing to a[10] in the last iteration of the loop, which is outside the bounds of the array. Remember, C arrays are indexed from 0, so an array defined as SomeType array[N]; has elements from array[0] to array[N-1].
Note that you can rewrite nCount() as a simple (non-recursive) function:
static inline int nCount(int n) { return (n + 1) * n / 2; }
(which would need to appear before it is called, of course). Or, if you're stuck using an archaic compiler that doesn't support C99 or C11, drop the inline keyword.
Given an array of size n. It contains numbers in the range 1 to n. Each number is present at
least once except for 2 numbers. Find the missing numbers.
eg. an array of size 5
elements are suppose 3,1,4,4,3
one approach is
static int k;
for(i=1;i<=n;i++)
{
for(j=0;j<n;j++)
{
if(i==a[j])
break;
}
if(j==n)
{
k++;
printf("missing element is", a[j]);
}
if(k==2)
break;}
another solution can be..
for(i=0;i
Let me First explain the concept:
You know that sum of natural numbers 1....n is
(n*(n+1))/2.Also you know the sum of square of sum of first n natural numbers 1,2....n is n*(n+1)*(2n+1)/6.Thus you could solve the above problem in O(n) time using above concept.
Also if space complexity is not of much consideration you could use count based approach which requires O(n) time and space complexity.
For more detailed solution visit Find the two repeating elements in a given array
I like the "use array elements as indexes" method from Algorithmist's link.
Method 5 (Use array elements as index)
Thanks to Manish K. Aasawat for suggesting this method.
traverse the list for i= 1st to n+2 elements
{
check for sign of A[abs(A[i])] ;
if positive then
make it negative by A[abs(A[i])]=-A[abs(A[i])];
else // i.e., A[abs(A[i])] is negative
this element (ith element of list) is a repetition
}
The only difference is that here it would be traversing 1 to n.
Notice that this is a single-pass solution that uses no extra space (besides storing i)!
Footnote:
Technically it "steals" some extra space -- essentially it is the counter array solution, but instead of allocating its own array of ints, it uses the sign bits of the original array as counters.
Use qsort() to sort the array, then loop over it once to find the missing values. Average O(n*log(n)) time because of the sort, and minimal constant additional storage.
I haven't checked or run this code, but you should get the idea.
int print_missing(int *arr, size_t length) {
int *new_arr = calloc(sizeof(int) * length);
int i;
for(i = 0; i < length; i++) {
new_arr[arr[i]] = 1;
}
for(i = 0; i < length; i++) {
if(!new_arr[i]) {
printf("Number %i is missing\n", i);
}
}
free(new_arr);
return 0;
}
Runtime should be O(2n). Correct me if I'm wrong.
It is unclear why the naive approach (you could use a bitfield or an array) of marking the items you have seen isn't just fine. O(2n) CPU, O(n/8) storage.
If you are free to choose the language, then use python's sets.
numbers = [3,1,4,4,3]
print set (range (1 , len (numbers) + 1) ) - set (numbers)
Yields the output
set([2, 5])
Here you go. C# solution:
static IEnumerable<int> FindMissingValuesInRange( int[] numbers )
{
HashSet<int> values = new HashSet<int>( numbers ) ;
for( int value = 1 ; value <= numbers.Length ; ++value )
{
if ( !values.Contains(value) ) yield return value ;
}
}
I see a number of problems with your code. First off, j==n will never happen, and that doesn't give us the missing number. You should also initialize k to 0 before you attempt to increment it. I wrote an algorithm similar to yours, but it works correctly. However, it is not any faster than you expected yours to be:
int k = 0;
int n = 5;
bool found = false;
int a[] = { 3, 1, 4, 4, 3 };
for(int i = 1; i <= n; i++)
{
for(int j = 0; j < n; j++)
{
if(a[j] == i)
{
found = true;
break;
}
}
if(!found)
{
printf("missing element is %d\n", i);
k++;
if(k==2)
break;
}
else
found = false;
}
H2H
using a support array you can archeive O(n)
int support[n];
// this loop here fills the support array with the
// number of a[i]'s occurences
for(int i = 0; i < n; i++)
support[a[i]] += 1;
// now look which are missing (or duplicates, or whatever)
for(int i = 0; i < n; i++)
if(support[i] == 0) printf("%d is missing", i);
**
for(i=0; i < n;i++)
{
while((a[i]!=i+1)&&(a[i]!=a[a[i]-1])
{
swap(a[i],a[a[i]-1]);
}
for(i=0;i< n;i++)
{
if(a[i]!=i+1)
printf("%d is missing",i+1); }
this takes o(n) time and o(1) space
========================================**
We can use the following code to find duplicate and missing values:
int size = 8;
int arr[] = {1, 2, 3, 5, 1, 3};
int result[] = new int[size];
for(int i =0; i < arr.length; i++)
{
if(result[arr[i]-1] == 1)
{
System.out.println("repeating: " + (arr[i]));
}
result[arr[i]-1]++;
}
for(int i =0; i < result.length; i++)
{
if(result[i] == 0)
{
System.out.println("missing: " + (i+1));
}
}
This is an interview question: Missing Numbers.
condition 1 : The array must not contain any duplicates.
The complete solution is :
public class Solution5 {
public static void main(String[] args) {
int a[] = { 1,8,6,7,10};
Arrays.sort(a);
List<Integer> list = new ArrayList<>();
int start = a[0];
for (int i = 0; i < a.length; i++) {
int ch = a[i];
if(start == ch) {
start++;
}else {
list.add(start);
start++;
//must do this
i--;
}
}//for
System.out.println(list);
}//main
}