It is efficient because it places each element in its correct position through a series of swaps, allowing the algorithm to run in time with minimal space overhead.
Key takeaways:
Cyclic sort is a comparison-based, in-place sorting algorithm designed for arrays with a fixed range of values, making it both efficient and straightforward.
The algorithm works by repeatedly placing elements in their correct positions through a series of swaps, cycling through the array.
Cyclic sort is particularly useful when the values in an array range from
to , minimizing extra space usage as it sorts directly within the array. The algorithm is unstable but is highly effective in solving specific problems like missing number or duplicate number detection.
It has a time complexity of
, making it highly efficient for certain scenarios, especially when sorting integers within a known range.
Sorting is a fundamental operation in computer science, allowing us to arrange data in a specific order for efficient analysis and decision-making. Various sorting algorithms have been developed, each with strengths and weaknesses. One such algorithm is cyclic sort, a simple and efficient algorithm that works particularly well when dealing with a range of values within a fixed interval.
Cyclic sort is a comparison-based sorting algorithm that works for arrays containing values within a specific range. It’s an in-place, unstable algorithm that aims to sort the elements by arranging them in their correct positions, one at a time, through a series of swaps. The basic idea behind cyclic sort is to iterate through the array and place each element in its intended position until the entire array is sorted. It is based on the insight that subsequences of numbers in the input array that are not in sorted order describe cycles and that placing each number in its correct position removes them.
In a cycle, numbers that are not in their correct index are essentially part of a loop, where each number belongs to a different position. For example, if a number,
Now, let’s look at the following illustration to get a better understanding of the algorithm:
The illustration above shows how we moved cyclically to sort the array.
Now that we know how the algorithm works, let’s look at the code for the algorithm:
def cyclic_sort(arr):n = len(arr)for i in range(n):while arr[i] != i + 1:correct_index = arr[i] - 1arr[i], arr[correct_index] = arr[correct_index], arr[i]return arr# Driver codedef main():nums = [[1, 3, 2, 5, 4],[2, 4, 5, 1, 3],[1, 2, 4, 3],[3, 1, 5, 6, 4, 2]]for i in range(len(nums)):print(i + 1, ".\tArray before cyclic sort = ", nums[i], sep="")print("\tArray after cyclic sort = ", cyclic_sort(nums[i]), sep="")print("-" * 100)if __name__ == '__main__':main()
Lines 2–3: We get the length of the array and traverse it.
Line 4: We move in the array cyclically until the current element is in its correct position.
Line 5: We calculate the correct index for the current element.
Line 6: We swap the current element with the element at its correct index.
Line 7: We return the sorted array.
If you're prepping for technical interviews, understanding these algorithms and patterns can be a game changer. For LeetCode pattern-based problems, check out our course on Coding Interview Patterns.
Cyclic sort is especially useful when dealing with arrays that contain consecutive integers within a fixed range. It is effective in the following cases:
Detecting missing numbers: In arrays where one or more elements are missing, cyclic sorting helps efficiently identify those missing numbers.
Finding duplicates: It can also be used to find duplicate numbers in an array, as it quickly places elements where they belong and identifies those that are out of place.
We also have a detailed Answer on When and why do we use cyclic sort?
Time complexity:
Space complexity:
To further enhance your knowledge and skills in coding interviews, we recommend a specially designed path, Educative 99. This path offers interactive lessons that give hands-on experience with coding problems and opportunities to test and refine your solutions.
Unstable sorting: Cyclic sort is unstable, meaning it doesn’t preserve the relative order of equal elements.
Limited use case: It is effective primarily for arrays with consecutive integers or specific ranges, limiting its general applicability.
Haven’t found what you were looking for? Contact Us
Free Resources