Consider the following sort procedure written in pseudo code: Exchange Sort of A
ID: 3810575 • Letter: C
Question
Consider the following sort procedure written in pseudo code:
Exchange Sort of Array X[]
For I = 0 to (number of array elements - 2), increment by 1
For J = (I + 1) to (number of array elements - 1), increment by
If X[I] is greater than X[J] then
temp = X[I]
X[I] = X[J]
X[J] = temp
Next J
Next I
Implement the sort procedure in main() without using pointers.Declare the array as follows using the test data shown:
int x[] = { 28, 87, -3, 45, 19 };
Use a for loop to print out the array before sorting and again after sorting. There should be no output within the sort procedure.
Explanation / Answer
#include <stdio.h>
void exchangeSort(int x[], int n)
{
int i, j;
for(i = 0; i <= n-2; i++)
{
for(j = i+1; j <= n-1; j++)
{
if (x[i] > x[j])
{
int temp = x[i];
x[i] = x[j];
x[j] = temp;
}
}
}
}
int main()
{
int x[] = {28, 87, -3, 45, 19};
int n = 5;
printf("Array before sorting: ");
int i;
for(i = 0; i < n; i++)
{
printf("%d ", x[i]);
}
printf(" ");
exchangeSort(x, n);
printf("Array after sorting: ");
for(i = 0; i < n; i++)
{
printf("%d ", x[i]);
}
printf(" ");
return 0;
}
sample output
Array before sorting: 28 87 -3 45 19
Array after sorting: -3 19 28 45 87