Circle sort algorithm can be visualized by drawing concentric circles on an array of integers. The elements of the array lying on the same circle diametrically opposite to each other are compared and if found in the wrong order they are swapped. This goes on in a recursive fashion in which the array is divided into sub-arrays on which the above process is repeated until we get pairs of sorted elements which when put together form a sorted array. In short below two steps are repeated while there are swap operations involved in the steps.
- Compare the first element to the last element, then the second element to the second last element, etc.
- Then split the array in two and recurse until there is only one single element in the array.
It can be better explained by the image below.
Below is the implementation of above algorithm.Â
CPP
// CPP implementation of Circle Sort#include<bits/stdc++.h>using namespace std;Â
// Function to perform circular swaps recursively// This function returns true if there was a swap// operation performed.bool circleSortRec(int a[], int low, int high){Â Â Â Â bool swapped = false;Â
    // base case    if (low == high)        return false;Â
    // storing the upper and lower bounds    // of list to be used later in the    // recursive case    int lo = low, hi = high;Â
    while (lo < hi)    {        // swaps the pair of elements        // if true        if (a[lo] > a[hi])        {            swap(a[lo], a[hi]);            swapped = true;        }        lo++;        hi--;    }Â
    // special case arises only for list    // of odd size    if (lo == hi)        if (a[lo] > a[hi + 1])        {            swap(a[low], a[hi+1]);            swapped = true;        }Â
    // recursive case to check the    // traverse lists as sub lists    int mid = (high - low) / 2;    bool firstHalf = circleSortRec(a, low, low+mid);    bool secondHalf = circleSortRec(a, low+mid+1, high);Â
    return swapped || firstHalf || secondHalf;}Â
// This function mainly calls circleSortRecvoid circleSort(int a[], int n){    // Keep calling circleSortRec while    // there is a swap operation.    while (circleSortRec(a, 0, n-1))    {       ;    }}Â
// Driver programint main(){Â Â Â Â int a[] = {6, 5, 3, 1, 8, 7, 2, 4};Â Â Â Â int n = sizeof(a)/sizeof(a[0]);Â
    printf("\nUnsorted : ");    for (int i=0; i<n; i++)        cout << a[i] << " ";Â
    circleSort(a, n);Â
    printf("\nSorted : ");    for (int i=0; i<n; i++)        cout << a[i] << " ";Â
    return 0;} |
Java
// Java implementation of Circle Sortimport java.io.*;import java.util.*;Â
class GFG {    // Java function to swap the elements of an array    public static void swap(int[] arr, int i, int j) {        int t=arr[i];        arr[i]=arr[j];        arr[j]=t;   }Â
// Function to perform circular swaps recursively// This function returns true if there was a swap// operation performed.public static boolean circleSortRec(int a[], int low, int high){    boolean swapped = false;       // base case    if (low == high)        return false;       // storing the upper and lower bounds    // of list to be used later in the    // recursive case    int lo = low, hi = high;       while (lo < hi)    {        // swaps the pair of elements        // if true        if (a[lo] > a[hi])        {            swap(a,lo,hi);            swapped = true;        }        lo++;        hi--;    }       // special case arises only for list    // of odd size    if (lo == hi)        if (a[lo] > a[hi + 1])        {            swap(a,low,hi+1);            swapped = true;        }       // recursive case to check the    // traverse lists as sub lists    int mid = (high - low) / 2;    boolean firstHalf = circleSortRec(a, low, low+mid);    boolean secondHalf = circleSortRec(a, low+mid+1, high);       return swapped || firstHalf || secondHalf;}   // This function mainly calls circleSortRecpublic static void circleSort(int a[], int n){    // Keep calling circleSortRec while    // there is a swap operation.    while (circleSortRec(a, 0, n-1))    {       ;    }}       // Driver code    public static void main(String[] args)    {        int a[] = {6, 5, 3, 1, 8, 7, 2, 4};        int n = a.length;           System.out.print("Unsorted : ");        for (int i=0; i<n; i++)            System.out.print(a[i]+" ");           circleSort(a, n);           System.out.print("\nSorted : ");        for (int i=0; i<n; i++)            System.out.print(a[i]+" ");    }}Â
// This code is contributed by Pushpesh Raj |
C#
// C# implementation of Circle Sortusing System;Â
class GFG {  // function to swap the elements of an array  public static void swap(int[] arr, int i, int j) {    int t = arr[i];    arr[i] = arr[j];    arr[j] = t;  }Â
  // Function to perform circular swaps recursively  // This function returns true if there was a swap  // operation performed.  public static bool circleSortRec(int[] a, int low, int high)  {    bool swapped = false;Â
    // base case    if (low == high)      return false;Â
    // storing the upper and lower bounds    // of list to be used later in the    // recursive case    int lo = low, hi = high;Â
    while (lo < hi)    {      // swaps the pair of elements      // if true      if (a[lo] > a[hi])      {        swap(a,lo,hi);        swapped = true;      }      lo++;      hi--;    }Â
    // special case arises only for list    // of odd size    if (lo == hi)      if (a[lo] > a[hi + 1])      {        swap(a,low,hi+1);        swapped = true;      }Â
    // recursive case to check the    // traverse lists as sub lists    int mid = (high - low) / 2;    bool firstHalf = circleSortRec(a, low, low+mid);    bool secondHalf = circleSortRec(a, low+mid+1, high);Â
    return swapped || firstHalf || secondHalf;  }Â
  // This function mainly calls circleSortRec  public static void circleSort(int[] a, int n)  {    // Keep calling circleSortRec while    // there is a swap operation.    while (circleSortRec(a, 0, n-1))    {      ;    }  }Â
  // Driver code  static public void Main ()  {    int[] a = {6, 5, 3, 1, 8, 7, 2, 4};    int n = a.Length;Â
    Console.Write("Unsorted : ");    for (int i = 0; i < n; i++)      Console.Write(a[i]+" ");Â
    circleSort(a, n);Â
    Console.Write("\nSorted : ");    for (int i = 0; i < n; i++)      Console.Write(a[i]+" ");  }}Â
// This code is contributed by Aman Kumar. |
Python3
# Python implementation of Circle Sortimport sysÂ
# Function to perform circular swaps recursively# This function returns true if there was a swap# operation performed.def circleSortRec(a, low, high):Â Â Â Â swapped = FalseÂ
    # base case    if (low == high):        return FalseÂ
    # storing the upper and lower bounds    # of list to be used later in the    # recursive case    lo, hi = low, highÂ
    while (lo < hi):        # swaps the pair of elements        # if true        if (a[lo] > a[hi]):            a[lo], a[hi] = a[hi], a[lo]            swapped = True        lo += 1        hi -= 1Â
    # special case arises only for list    # of odd size    if (lo == hi):        if (a[lo] > a[hi + 1]):            a[low], a[hi+1] = a[hi+1], a[low]            swapped = TrueÂ
    # recursive case to check the    # traverse lists as sub lists    mid = (high - low) // 2    firstHalf = circleSortRec(a, low, low+mid)    secondHalf = circleSortRec(a, low+mid+1, high)Â
    return swapped or firstHalf or secondHalfÂ
# This function mainly calls circleSortRecdef circleSort(a, n):    # Keep calling circleSortRec while    # there is a swap operation.    while (circleSortRec(a, 0, n-1)):        passÂ
# Driver programa = [6, 5, 3, 1, 8, 7, 2, 4]n = len(a)Â
print("\nUnsorted : ", end="")for i in range(n):Â Â Â Â print(a[i], end=" ")Â
circleSort(a, n)Â
print("\nSorted : ", end="")for i in range(n):Â Â Â Â print(a[i], end=" ") |
Javascript
// Function to perform circular swaps recursively// This function returns true if there was a swap// operation performed.function circleSortRec(a, low, high) {let swapped = false;Â
// base caseif (low === high) {return false;}Â
// storing the upper and lower bounds// of list to be used later in the// recursive caselet lo = low, hi = high;Â
while (lo < hi) {// swaps the pair of elements// if trueif (a[lo] > a[hi]) {[a[lo], a[hi]] = [a[hi], a[lo]];swapped = true;}lo++;hi--;}Â
// special case arises only for list// of odd sizeif (lo === hi) {if (a[lo] > a[hi + 1]) {[a[low], a[hi+1]] = [a[hi+1], a[low]];swapped = true;}}Â
// recursive case to check the// traverse lists as sub listslet mid = Math.floor((high - low) / 2);let firstHalf = circleSortRec(a, low, low + mid);let secondHalf = circleSortRec(a, low + mid + 1, high);Â
return swapped || firstHalf || secondHalf;}Â
// This function mainly calls circleSortRecfunction circleSort(a, n) {Â
// Keep calling circleSortRec while// there is a swap operation.while (circleSortRec(a, 0, n-1)) {Â
// Do nothing}}Â
// Driver programlet a = [6, 5, 3, 1, 8, 7, 2, 4];let n = a.length;Â
console.log("\nUnsorted : ", a.join(" "));Â
circleSort(a, n);Â
console.log("\nSorted : ", a.join(" ")); |
Output :
Unsorted : 6 5 3 1 8 7 2 4 Sorted : 1 2 3 4 5 6 7 8
Time Complexity: O(N2)
Auxiliary Space: O(1)
References : SourceForge This article is contributed by Palash Nigam . If you like neveropen and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the neveropen main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

