šŸ“Šāš”Beginner

Sort Array in Ascending Order

Sort from low to high

Sorting an array in ascending order arranges elements from smallest to largest. This example uses a simple selection sort approach.

C Program to Sort Array in Ascending Order

sort_ascending.c
C
1#include <stdio.h>
2
3int main() {
4 int arr[] = {64, 34, 25, 12, 22, 11, 90};
5 int n = sizeof(arr) / sizeof(arr[0]);
6
7 // Selection Sort - Ascending
8 for (int i = 0; i < n - 1; i++) {
9 int minIdx = i;
10
11 // Find minimum in unsorted part
12 for (int j = i + 1; j < n; j++) {
13 if (arr[j] < arr[minIdx]) {
14 minIdx = j;
15 }
16 }
17
18 // Swap minimum with first unsorted element
19 int temp = arr[minIdx];
20 arr[minIdx] = arr[i];
21 arr[i] = temp;
22 }
23
24 printf("Sorted array (ascending): ");
25 for (int i = 0; i < n; i++) {
26 printf("%d ", arr[i]);
27 }
28
29 return 0;
30}
Output

Sorted array (ascending): 11 12 22 25 34 64 90

šŸŽÆ Key Takeaways

āœ“Selection sort: find min, swap to front
āœ“Time complexity: O(n²)