C program to sort an array in ascending order
In this post, you will learn how to sort an array in ascending order using the C programming language. Such a type of question is generally asked in programming interviews.
C program to sort an array
There are different ways to sort the array, here we have used nested for loop to sort an array. The outer for loop will select an element, and the inner for loop allows us to compare the selected element with the rest of the elements.
Algorithm
STEP 1: START
STEP 2: INITIALIZE array arr[]
STEP 3: SET temp =0
STEP 4: length= sizeof(arr)/sizeof(arr[0])
STEP 5: SET i=0. REPEAT STEP 6 and STEP 7 UNTIL i<length
STEP 6: PRINT arr[i]
STEP 7: i=i+1.
STEP 8: SET i=0. REPEAT STEP 9 to STEP UNTIL i<n
STEP 9: SET j=i+1. REPEAT STEP 10 UNTIL j<length
STEP 10: if(arr[i]>arr[j]) then
temp = arr[i]
arr[i]=arr[j]
arr[j]=temp
STEP 11: j=j+1.
STEP 12: i=i+1.
STEP 13: SET i=0. REPEAT STEP 14 and STEP 15 UNTIL i<length
STEP 14: PRINT arr[i]
STEP 15: i=i+1.
STEP 16: RETURN 0.
STEP 17: END.
In the given C program, we create an array of fixed size, iterate via a for loop, and print array elements. To sort the array elements, make a nested loop. Within the nested loop, we compare each element to the remaining elements below it. If the element is greater than the element present below it, then interchange that. At the end of the nested loop, we have an array with elements arranged in ascending order.
#include <stdio.h>
int main()
{
//Initialize array
int arr[] = {17, 41, 92, 52, 18, 55};
int temp = 0;
//Getting length of array arr
int len = sizeof(arr)/sizeof(arr[0]);
//Displaying elements of original array
printf("Original Array: \n");
for (int i = 0; i < len; i++) {
printf("%d ", arr[i]);
}
// Sorting the array in ascending order
for (int i = 0; i < len; i++) {
for (int j = i+1; j < len; j++) {
if(arr[i] > arr[j]) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
printf("\n");
//Displaying elements of array after sorting
printf("Elements of Array in Ascending Order: \n");
for (int i = 0; i < len; i++) {
printf("%d ", arr[i]);
}
return 0;
}
Output of the above code:
Original Array:
17 41 92 52 18 55
Elements of Array in Ascending Order:
17 18 41 52 55 92
Related Articles
Convert double to int JavaAverage of two numbers in C
Swapping of two numbers in C using pointers
Armstrong number in C using function
Binary to decimal C program
Sum of array elements in C
Random number generator in C
Factorial program in c using while loop
Student mark sheet program in C
C program to sort names in alphabetical order
C program to find largest number in an array
Print first 10 natural numbers using while loop in C
Simple calculator program in C
C program for simple interest
Swap two numbers without using third variable in C
Radix sort program in C
Bit stuffing program in C
Bubble sort program in C
Decimal to hexadecimal in C
Hexadecimal to decimal in C
Quick sort program in C