C Program to Sort an Array in Ascending Order
Sorting an array in ascending order means arranging the elements in the order from smallest element to largest element.
The easiest way to sort an array in C is by using qsort() function. This function needs a comparator to know how to compare the values of the array. Let's look at a simple example:
#include <stdio.h>
#include <stdlib.h>
// Custom comparator
int comp(const void* a, const void* b) {
// If a is smaller, positive value will be returned
return (*(int*)a - *(int*)b);
}
int main() {
int arr[] = { 2 ,6, 1, 5, 3, 4 };
int n = sizeof(arr) / sizeof(arr[0]);
// Sort the array using qsort
qsort(arr, n, sizeof(int), comp);
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
return 0;
}
Output
1 2 3 4 5 6
Explanation: The comp() function is the comparator that returns difference between the first and second element, otherwise returns 0 or negative value. This will sort the array in ascending order.
C language only provides the built-in implementation of quicksort algorithm. If you want to use other sorting algorithm apart from quicksort, you have to manually implement it.
Table of Content
Using Selection Sort
Selection sort is a simple sorting algorithm that repeatedly finds the minimum element from the unsorted part of the array and places it at its position in the sorted part of the array until the complete array is sorted.
#include <stdio.h>
// Selection sort implementation
void selectionSort(int arr[], int n) {
for (int i = 0; i < n - 1; i++) {
int min = i;
for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[min])
min = j;
}
if (min != i) {
int temp = arr[min];
arr[min] = arr[i];
arr[i] = temp;
}
}
}
int main() {
int arr[] = { 2 ,6, 1, 5, 3, 4 };
int n = sizeof(arr) / sizeof(arr[0]);
// Perform Selection Sort
selectionSort(arr,n);
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
return 0;
}
Output
1 2 3 4 5 6
Using Bubble Sort
In Bubble Sort Algorithm, we repeatedly swap adjacent elements if they are in the wrong order. This process is repeated until the array is sorted.
#include <stdio.h>
// Bubble sort implementation
void bubbleSort(int arr[], int n) {
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
int main() {
int arr[] = { 2 ,6, 1, 5, 3, 4 };
int n = sizeof(arr) / sizeof(arr[0]);
// Perform bubble sort
bubbleSort(arr,n);
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
return 0;
}
Output
1 2 3 4 5 6