\$\begingroup\$
\$\endgroup\$
5
I made this program which sorts the elements of an array in an ascending order and then prints out the sorted array.
#include <stdio.h>
int main()
{
int size, array[1000];
scanf("%d", &size);
for (int i=0; i<size; i++)
{
scanf("%d", array[i]);
}
int count, max, pos;
count = size-1;
max = array[0];
for (int j=0; j<size; j++)
{
for (int k=0; k<=count; k++)
{
if (array[k]>max)
{
max=array[k];
pos=k;
}
array[count]=array[pos];
array[pos]=array[count];
count--;
}
}
for (int l=0; l<size; l++)
{
printf("%d ", array[l]);
}
return 0;
}
Soha Farhin PineSoha Farhin Pine
asked Aug 13, 2017 at 7:47
1 Answer 1
\$\begingroup\$
\$\endgroup\$
This element swap won't work:
array[count]=array[pos];
array[pos]=array[count];
You are assigning b to a, and then immediately a to b. In C, you will need to use a temporary variable for this operation, like so:
int buffer;
buffer=array[count];
array[count]=array[pos];
array[pos]=buffer;
lang-c
temp
,day[n]
. Sorry. It's all part of a more complex problem from Codeforces.temp
is a commonly used variable name in C/C++; it's like a count variable. That array namedday
is for a wholly different purpose. That is, how long it takes to learn a particular instrument. All of this is completely irrelevant to my actual focus. So, I decided to leave it out. :-) \$\endgroup\$array[pos]=array[count];
- I can guess that meant to swap the elments, but it does not work that way. Seriously though, use theqsort
function for Codeforces. \$\endgroup\$