Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Convert an Array to reduced form using Vector of pairs
Next article icon

Sort an Array which contains 1 to n values using Mathematical Formula

Last Updated : 10 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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(" ")); 

Output
1 2 3 4 5 




Next Article
Convert an Array to reduced form using Vector of pairs
author
coder001
Improve
Article Tags :
  • Algorithms
  • Arrays
  • DSA
  • Sorting
  • Natural Numbers
Practice Tags :
  • Algorithms
  • Arrays
  • Sorting

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) T
    7 min read
  • Convert an Array to reduced form using Vector of pairs
    Given an array with n distinct elements, convert the given array to a form where all elements are in range from 0 to n-1. The order of elements is same, i.e., 0 is placed in place of smallest element, 1 is placed for second smallest element, ... n-1 is placed for largest element. Input: arr[] = {10,
    11 min read
  • Sort an array containing two types of elements
    This problem appears in multiple forms as mentioned below. If we take a closer look at the below problems, we can notice that the problem is mainly a variation of partition algorithm in QuickSort. Table of Content Sort a Binary ArrayMove all zeros to end of array Separate Even and Odd NumbersSeparat
    3 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 Content Sort an array of 0s, 1s and 2sThree way partitioning
    4 min read
  • C Program to Sort an array of names or strings
    Given an array of strings in which all characters are of the same case, write a C function to sort them alphabetically. The idea is to use qsort() in C and write a comparison function that uses strcmp() to compare two strings. C/C++ Code #include <stdio.h> #include <stdlib.h> #include
    2 min read
  • Program to sort an array of strings using Selection Sort
    Given an array of strings, sort the array using Selection Sort. Examples: Input : paper true soap floppy flower Output : floppy, flower, paper, soap, true Prerequisite : Selection Sort. C/C++ Code // C++ program to implement selection sort for // array of strings. #include <bits/stdc++.h> #inc
    7 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
  • Sort an array using Bubble Sort without using loops
    Given an array arr[] consisting of N integers, the task is to sort the given array by using Bubble Sort without using loops. Examples: Input: arr[] = {1, 3, 4, 2, 5}Output: 1 2 3 4 5 Input: arr[] = {1, 3, 4, 2}Output: 1 2 3 4 Approach: The idea to implement Bubble Sort without using loops is based o
    9 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
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences