-
-
Notifications
You must be signed in to change notification settings - Fork 7.3k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Explanation: Cycle Sort is an in-place, non-comparing sorting algorithm. It minimizes the number of writes to the original array, making it useful when writing to the data is costly. It works by selecting an item and finding its correct position in the sorted part of the array, then repeating this process for the remaining items.
- Loading branch information
1 parent
6376bf4
commit 4928c3f
Showing
1 changed file
with
53 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,53 @@ | ||
-->Explanation: Cycle Sort is an in-place, non-comparing sorting algorithm. It minimizes the number of writes to the original array, | ||
-->making it useful when writing to the data is costly. | ||
-->It works by selecting an item and finding its correct position in the sorted part of the array, then repeating this process for the remaining items. | ||
|
||
#include <iostream> | ||
using namespace std; | ||
void cycleSort(int arr[], int n) { | ||
for (int cycleStart = 0; cycleStart < n - 1; cycleStart++) { | ||
int item = arr[cycleStart]; | ||
int pos = cycleStart; | ||
for (int i = cycleStart + 1; i < n; i++) { | ||
if (arr[i] < item) { | ||
pos++; | ||
} | ||
} | ||
if (pos == cycleStart) { | ||
continue; | ||
} | ||
while (item == arr[pos]) { | ||
pos++; | ||
} | ||
swap(item, arr[pos]); | ||
while (pos != cycleStart) { | ||
pos = cycleStart; | ||
for (int i = cycleStart + 1; i < n; i++) { | ||
if (arr[i] < item) { | ||
pos++; | ||
} | ||
} | ||
while (item == arr[pos]) { | ||
pos++; | ||
} | ||
swap(item, arr[pos]); | ||
} | ||
} | ||
} | ||
|
||
int main() { | ||
int n; | ||
cout << "Enter the number of elements: "; | ||
cin >> n; | ||
int arr[n]; | ||
cout << "Enter the elements: "; | ||
for (int i = 0; i < n; i++) { | ||
cin >> arr[i]; | ||
} | ||
cycleSort(arr, n); | ||
cout << "Sorted array: "; | ||
for (int i = 0; i < n; i++) { | ||
cout << arr[i] << " "; | ||
} | ||
return 0; | ||
} |