Sort an Array which contains 1 to n values using Mathematical Formula
Last Updated :
10 Oct, 2024
Given an array arr[] of size n, having distinct integers from 1 to n, the task is to sort the array.
Input: arr[] = { 2, 1, 5, 4, 3}
Output: {1, 2, 3, 4, 5}
Input: arr[] = {1, 2, 3, 4, 5, 6}
Output: {1, 2, 3, 4, 5, 6}
We have already discussed different approaches to solve the problem in the post Sort an array which contains 1 to n values. In this post, we will discuss a mathematical approach to sort the array.
Using Mathematical Formula - O(n) Time and O(1) Space
The idea is to traverse the input array and for each element arr[i], place it at its correct index, that is (arr[i] - 1). The problem with this approach is that if we update arr[arr[i] - 1] with arr[i] we will end up overwriting the element at index (arr[i] - 1). To solve this problem, we can find the maximum value in the array, that is (n + 1) and use it to store the original as well as the updated value at each index.
Let's say for any index i, we have the current element as arr[i]. We know that the correct index for arr[i], say correctIdx is (arr[i] - 1). Now, instead of overwriting arr[correctIdx], we add (arr[i] * (n + 1)) to arr[correctIdx]. This is because we can get the original value by arr[i] % (n + 1) and updated value by arr[i] / (n + 1).
After traversing the array and modifying each index, traverse again and update arr[i] to arr[i] / (n + 1) to get the sorted values.
C++
// C++ Program to sort distinct integer array from
// 1 to n using Mathematical formula
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
// function to sort the array
void sortArr(vector<int> &arr) {
int n = arr.size();
for(int i = 0; i < n; i++) {
int originalVal = arr[i] % (n + 1);
int correctIdx = originalVal - 1;
arr[correctIdx] += originalVal * (n + 1);
}
for(int i = 0; i < n; i++)
arr[i] = arr[i] / (n + 1);
}
int main() {
vector<int> arr = { 2, 1, 5, 4, 3 };
sortArr(arr);
for(int i = 0; i < arr.size(); i++)
cout << arr[i] << " ";
return 0;
}
C
// C Program to sort distinct integer array from
// 1 to n using Mathematical formula
#include <stdio.h>
// function to sort the array
void sortArr(int *arr, int n) {
for (int i = 0; i < n; i++) {
int originalVal = arr[i] % (n + 1);
int correctIdx = originalVal - 1;
arr[correctIdx] += originalVal * (n + 1);
}
for (int i = 0; i < n; i++) {
arr[i] = arr[i] / (n + 1);
}
}
int main() {
int arr[] = { 2, 1, 5, 4, 3 };
int n = sizeof(arr) / sizeof(arr[0]);
sortArr(arr, n);
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
return 0;
}
Java
// Java Program to sort distinct integer array from
// 1 to n using Mathematical formula
import java.util.Arrays;
class GfG {
// function to sort the array
static void sortArr(int[] arr) {
int n = arr.length;
for (int i = 0; i < n; i++) {
int originalVal = arr[i] % (n + 1);
int correctIdx = originalVal - 1;
arr[correctIdx] += originalVal * (n + 1);
}
for (int i = 0; i < n; i++)
arr[i] = arr[i] / (n + 1);
}
public static void main(String[] args) {
int[] arr = { 2, 1, 5, 4, 3 };
sortArr(arr);
for (int i = 0; i < arr.length; i++)
System.out.print(arr[i] + " ");
}
}
Python
# Python Program to sort distinct integer array from
# 1 to n using Mathematical formula
def sortArr(arr):
n = len(arr)
for i in range(n):
originalVal = arr[i] % (n + 1)
correctIdx = originalVal - 1
arr[correctIdx] += originalVal * (n + 1)
for i in range(n):
arr[i] = arr[i] // (n + 1)
if __name__ == "__main__":
arr = [2, 1, 5, 4, 3]
sortArr(arr)
for i in range(len(arr)):
print(arr[i], end=" ")
C#
// C# Program to sort distinct integer array from
// 1 to n using Mathematical formula
using System;
class GfG {
// function to sort the array
static void sortArr(int[] arr) {
int n = arr.Length;
for (int i = 0; i < n; i++) {
int originalVal = arr[i] % (n + 1);
int correctIdx = originalVal - 1;
arr[correctIdx] += originalVal * (n + 1);
}
for (int i = 0; i < n; i++)
arr[i] = arr[i] / (n + 1);
}
static void Main() {
int[] arr = { 2, 1, 5, 4, 3 };
sortArr(arr);
for (int i = 0; i < arr.Length; i++) {
Console.Write(arr[i] + " ");
}
}
}
JavaScript
// JavaScript Program to sort distinct integer array from
// 1 to n using Mathematical formula
function sortArr(arr) {
let n = arr.length;
for (let i = 0; i < n; i++) {
let originalVal = arr[i] % (n + 1);
let correctIdx = originalVal - 1;
arr[correctIdx] += originalVal * (n + 1);
}
for (let i = 0; i < n; i++)
arr[i] = Math.floor(arr[i] / (n + 1));
}
let arr = [2, 1, 5, 4, 3];
sortArr(arr);
console.log(arr.join(" "));
Similar Reads
Sort an array which contain 1 to n values We are given an array that contains 1 to n elements, our task is to sort this array in an efficient way. We are not allowed to simply copy the numbers from 1 to n.Examples : Input : arr[] = {2, 1, 3};Output : {1, 2, 3}Input : arr[] = {2, 1, 4, 3};Output : {1, 2, 3, 4} Native approach - O(n Log n) Ti
7 min read
How to Sort a Multi-dimensional Array by Value What is Sorting?Arranging data in an increasing or decreasing fashion according to their values is called Sorting. Below are shown some processes for sorting arrays of several dimensions. Sorting a 1-Dimensional array:We can sort any Dimensional array using the sort method in C++. Syntax: sort(arr,
11 min read
Sort an array having 3 types of Values We are given an array containing three different types of elements, and the task is to sort the array. This problem has been asked in various forms, and in this article, we will explore the three most common forms of this problem.Table of ContentSort an array of 0s, 1s and 2sThree way partitioning a
4 min read
Sort given Array based on the fractional values Given an array arr[] that contains N real numbers. The task is to sort the array in decreasing order of the Fractional Values Note: If the values of the fractional part are same then sort those elements in Decreasing order of their Integer Values. Examples: Input: arr[] = { 8.33, -3.85, 1.999, 6.33,
10 min read
Check whether the given String is good for any ascending Array or not Given a string S of length N. Consider any ascending array A[] such that each A[i] > 0 for all (1 <= i <= N) and some conditions, the task is to output YES/NO, by checking that the above-given conditions are true for all possible ascending A[]'s or not with given S. Sum up all the elements
7 min read