Hoai Nguyen Trung - 1 year ago 58

C Question

I know how to sort an array by ascending order, but not quite catch it when just sort first n (in my case, 4) elements. I tried to add a count value and do-while loop but it still sort all the element. Any idea?

`do{`

for(i=0; i<size; i++){

for(j=i+1; j<size; j++){

if(arr[j] < arr[i]){

temp = arr[i];

arr[i] = arr[j];

arr[j] = temp;

count++;

}

}

}

}while(count<5)

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

I know how to sort an array by ascending order, but not quite catch it when just sort first

`n`

elements

** It's not much different**.

Instead of using `for`

loop to sort elements of the whole array, use it only for first `n`

elements by changing the value of `size`

to the value of `n`

```
int n; //variable to store the value of 'n'
scanf("%d", &n); //scan value of 'n'
size = n; //assigning value of 'n' to 'size'
for(i=0; i < size; i++)
{
for(j = i+1; j < size; j++)
{
if(arr[j] < arr[i])
{
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
```

or by

using `n`

instead of `size`

if you require value of `size`

later in the program.

```
int n; //variable to store the value of 'n'
scanf("%d", &n); //scan value of 'n'
for(i=0; i < n; i++)
{
for(j = i+1; j < n; j++)
{
if(arr[j] < arr[i])
{
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
```

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**