'This program takes a number of elements of an array, (positive numbers only), and sorts them from smallest to largest [closed]
How does the function sort work. And what parameters does this pass into the write function so that it writes out numbers from smallest to largest. The for in a for loop part confuses me the most... What do we need the "pom" for.
#define MAX 100
int read(double[]);
void sort(double[], int);
void write(double[], int);
int main()
{
double niz[MAX];
int n;
n = read(niz);
sort(niz, n);
printf("Sorted:");
write(niz, n);
return 0;
}
int read(double niz[])
{
int i, n;
do
{
printf("n=");
scanf_s("%d", &n);
} while (n < 1 || n > MAX);
for (i = 0; i < n; i++)
{
printf("%d. broj: ", i + 1);
scanf_s("%lf", &niz[i]);
}
return n;
}
void sort(double niz[], int n)
{
int i, j;
for (i = 0; i < n - 1; i++)
for (j = i + 1; j < n; j++)
if (niz[i] > niz[j])
{
double pom = niz[i];
niz[i] = niz[j];
niz[j] = pom;
}
}
void write(double niz[], int n)
{
int i;
for (i = 0; i < n; i++)
printf(" %.2lf", niz[i]);
}
Solution 1:[1]
This function
void sort(double niz[], int n)
{
int i, j;
for (i = 0; i < n - 1; i++)
for (j = i + 1; j < n; j++)
if (niz[i] > niz[j])
{
double pom = niz[i]; niz[i] = niz[j]; niz[j] = pom;
}
}
implements the selection sort algorithm with redundant swaps.
For each element of the array selected in the outer for loop the followed elements in the inner for loop are compared with the selected element and if an element in the inner for loop is less than the selected element then the two elements are swapped.
double pom = niz[i]; niz[i] = niz[j]; niz[j] = pom;
the auxiliary variable pom is used to store temporary the value of element niz[i] that allows to swap the values of niz[i] and niz[j].
for example of you have the array
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Vlad from Moscow |
