DEV Community

Prashant Mishra
Prashant Mishra

Posted on • Edited on

Circular sorting algorithm

Circular sorting
Pre-requisite : elements of the array should be between 1 to length of the array
In Circular Sorting elements are placed at their natural indexs
Example:if the array is [5,4,2,1,3] => [1,2,3,4,5]

import java.util.*;

public class Main {
    public static void main(String[] args) {
      int arr[] = {5,4,2,1,3};
      findDuplicates(arr);
      for(int i =0;i<arr.length;i++){
        System.out.println(arr[i]);
      }
  }
  public static void findDuplicates(int[] nums){
        int i =0,n  = nums.length;
        while(i<n){
            int j = nums[i]-1;
            if(nums[i]!=nums[j]){
                swap(nums,i,j);
            }
            else i++;
        }

    }
    public static void swap(int[] nums,int i ,int j){
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }
}
Enter fullscreen mode Exit fullscreen mode

Usage:

  • Its useful in identifying duplicates in the array

  • It can also be used to find missing elements in the array

Example : Finding missing element in the array of length n where the elements of the array are in the range 0<=element<=n

class Solution {
    public int missingNumber(int[] nums) {
        int i =0,n = nums.length;
        // circular sorting
        while(i<n){
            int  j = nums[i]-1;
            if(j<0) {i++ ; continue;}
            else if(nums[i]!=nums[j]) swap(nums,i,j);
            else i++;
        }
        int missing = 0;
        for(int k = 0;k<nums.length;k++){
            if(k!=nums[k]-1){ missing = k+1; break;}
        }
        return missing;

    }
    public void swap(int[] nums,int i,int j){
        int temp  = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

Great read:

Is it Time to go Back to the Monolith?

History repeats itself. Everything old is new again and I’ve been around long enough to see ideas discarded, rediscovered and return triumphantly to overtake the fad. In recent years SQL has made a tremendous comeback from the dead. We love relational databases all over again. I think the Monolith will have its space odyssey moment again. Microservices and serverless are trends pushed by the cloud vendors, designed to sell us more cloud computing resources.

Microservices make very little sense financially for most use cases. Yes, they can ramp down. But when they scale up, they pay the costs in dividends. The increased observability costs alone line the pockets of the “big cloud” vendors.

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay