Example:
If the elements of array are: 20, 2, 10, 6, 52, 31, 0, 45, 79, 40
Array sorted in ascending order: 0, 2, 6, 10, 20, 31, 40, 45, 52, 79
Required knowledge:
Basic C programming, If else, For loop, ArrayAlgorithm:
Here we will use basic algorithm to sort arrays in ascending order:Step 1: Read elements in array.
Step 2: Set i=0
Step 3: Set j=i+1
Step 4: If array[i] > array[j] then swap value of array[i] and array[j].
Step 5: Set j=j+1
Step 6: Repeat Step 4-5 till j<n (Where n is the size of the array)
Step 7: Set i=i+1
Step 8: Repeat Step 3-7 till i<n
Program:
/** * C program to sort elements of array in ascending order */ #include <stdio.h> int main() { int arr[100]; int size, i, j, temp; /* * Read size of array and elements in array */ printf("Enter size of array: "); scanf("%d", &size); printf("Enter elements in array: "); for(i=0; i<size; i++) { scanf("%d", &arr[i]); } /* * Array sorting code */ for(i=0; i<size; i++) { for(j=i+1; j<size; j++) { /* * If there is a smaller element towards right of the array then swap it. */ if(arr[j] < arr[i]) { temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } } /* * Prints the sorted array */ printf("\nElements of array in sorted ascending order: "); for(i=0; i<size; i++) { printf("%d\t", arr[i]); } return 0; }
Output
Enter size of array: 10
Enter elements in array: 20 2 10 6 52 31 0 45 79 40
Elements of array in sorted ascending order: 0 2 6 10 20 31 40 45 52 79
Enter elements in array: 20 2 10 6 52 31 0 45 79 40
Elements of array in sorted ascending order: 0 2 6 10 20 31 40 45 52 79
Happy coding ;)
You may also like
- Array and Matrix programming exercises index.
- C program to sort elements of array in descending order.
- C program to sort even and odd elements of array separately.
- C program to put even and odd elements of array in two separate array.
- C program to search an element in array.
- C program to insert an element in array.
- C program to delete an element from array.
- C program to delete all duplicate elements from array.
- C program to check Identity matrix.
- C program to check whether a number is Prime number or not.
- C program to check whether a number is Armstrong number or not.
- C program to check whether a number is Strong number or not.
- C program to check whether a number is Perfect number or not.