C Exercises: Sort n numbers in range from 0 to n^2
C Array: Exercise-79 with Solution
Write a program in C to sort n numbers in the range from 0 to n^2.
Pictorial Presentation:

Sample Solution:
C Code:
#include <stdio.h>
int countSort(int arr1[], int n, int exp)
{
int output[n];
int i, ctr[n] ;
for (int i=0; i < n; i++)
ctr[i] = 0;
for (i = 0; i < n; i++)
ctr[ (arr1[i]/exp)%n ]++;
for (i = 1; i < n; i++)
ctr[i] += ctr[i - 1];
for (i = n - 1; i >= 0; i--)
{
output[ctr[ (arr1[i]/exp)%n] - 1] = arr1[i];
ctr[(arr1[i]/exp)%n]--;
}
for (i = 0; i < n; i++)
arr1[i] = output[i];
}
void sortArray(int arr1[], int n)
{
countSort(arr1, n, 1);
countSort(arr1, n, n);
}
void printBothArr(int arr1[], int n)
{
for (int i = 0; i < n; i++)
printf("%d ",arr1[i]);
}
int main()
{
int arr1[] = {37, 62, 52, 7, 48, 3, 15, 61};
int n = sizeof(arr1)/sizeof(arr1[0]);
printf("The given array is: ");
printBothArr(arr1, n);
sortArray(arr1, n);
printf("\nSorted array is: ");
printBothArr(arr1, n);
return 0;
}
Sample Output:
The given array is: 37 62 52 7 48 3 15 61 Sorted array is: 3 7 15 37 48 52 61 62
Flowchart:

C Programming Code Editor:
Improve this sample solution and post your code through Disqus.
Previous: Write a program in C to find four array elements whose sum is equal to given number.
Next: Write a program in C to count all distinct pairs for a specific difference.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
C Programming: Tips of the Day
C Programming - What is the argument for printf that formats a long?
Put an l (lowercased letter L) directly before the specifier.
unsigned long n; long m; printf("%lu %ld", n, m);
Ref : https://bit.ly/3dIwfkP
- Weekly Trends
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join
- JavaScript functions Exercises
- Python Tutorial
- Python Array Exercises
- SQL Cross Join
- C# Sharp Array Exercises