Sort the elements of an array A in ascending order.
Method: Starting again each time at the beginning of the table, we carry out several times the following treatment: We propagate, by successive permutations, the largest element of the array towards the end of the array (like a bubble that goes back to the surface of a liquid).
Implement the algorithm considering that:
- The part of the table (on the right) where there were no permutations is sorted.
- If no swapping has occurred, the array is sorted.
Difficulty level
Video recording
This exercise is mostly suitable for students
#include <stdio.h>
#define size 50
int main()
{
int A[size];
int N, i , j, aux;
int exchange;
do {
printf("Enter N: ");
scanf("%d",&N);
}while(N<=0 || N>size);
printf("Enter %d elements: ", N);
for(i=0; i<N; i++)
scanf("%d",&A[i]);
exchange = 1;
for(i=N-1; i>0 && exchange==1; i--)
{
exchange = 0;
for(j=0 ; j< i; j++)
if(A[j]>A[j+1])
{
exchange = 1;
aux = A[j];
A[j]=A[j+1];
A[j+1]=aux;
}
}
printf("\n\nAfter sorting\n\n");
for(i=0;i<N;i++)
printf("%d ",A[i]);
return 0;
}
Back to the list of exercises
Looking for a more challenging exercise, try this one !!
Forest of Binary Search Trees