I am trying to implement bubble sort in C. The question has a constraint that:
The first line should be the number of elements in the array
The second line is the input
For example:
first line: 5
second line: 5 4 2 8 1
I need to read the second line an storing it into an array to be able to sort them. I have searched on the internet and found that getline()
helps us to read a line. The issue here is that if I want to use getline()
I need to know how many bits are going to read so I can allocate enough space for it, but here we do not know how along a number would be.
The code I have written is as follow:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char ** argv){
int sizeOfArray;
// getting the number of inputs from the second line.
// Then go to the third line
scanf("[^\n]%d[^\n]", &sizeOfArray);
int inputArray[sizeOfArray];
//------------------------------------
// This bit I have stuck. I do not know how to solve it
for(int iteration = 0; iteration<sizeOfArray; iteration++)
{
("%d ", &inputArray[iteration]);
}
// ----------------------------
int arrSizeCopy = sizeOfArray;
int mediator = 0 ;
while(arrSizeCopy> 0)
{
for(int i=0; i< arrSizeCopy-1; i++)
{
if(inputArray[i]>inputArray[i+1])
{
mediator = inputArray[i];
inputArray[i] = inputArray[i+1];
inputArray[i+1] = mediator;
}
}
arrSizeCopy--;
}
for (int i=0; i<sizeOfArray; i++)
{
printf("%d ", inputArray[i]);
}
return 0;
}
I really appreciate if someone could help me to find the answer for it.