Firstly, sorting is arranging the given elements in ascending or descending order. For this we'll use dynamic memory allocation and concept of swapping. As you can see in line number 10 in the code, we have dynamically allocated an array 'A' which takes n number of inputs.
If you have not heard of Dynamic memory allocation, then refer here.
In line number 17, we have a for loop that compares selected element with its previous one. For example, THE element of index 1 is compared with element of index 0 as so on. Next there is a if statement that compares if the element in the previous index is greater than the next index element, then if statement is executed.
Later swapping concept is used, in our case we have used an 'temp' variable, following example will explain the same:
suppose A[i]=20 and A[j]=10, so
temp=A[i] assigns temp= 20 then,
A[i]=A[j] assigns A[i]= 10 and,
A[j]=temp gives A[j]=20.
thus our given values are swapped. Later we have printed the array.
Code contributed by Anmol Sinha.
No comments:
Post a Comment