Share the joy
The characteristic of circle sort is that it takes least swap operation than any other sorting algorithm.
Given an integer array a[], it loops the element start_pos from a[0] to a[length-2]. Each time, find the right position(next_pos) for a[start_pos]. And we should still find the position for a[next_pos], and update the next_pos on and on, until next_pos goes to start_pos. The above operation happens in certain elements, which one replace another one like a circle.
- public static void circleSort(int[] a) {
- if (a == null || a.length == 1) {
- return;
- }
- for (int start_pos = 0; start_pos < a.length – 1; start_pos++) {
- int next_pos = start_pos;
- for (int i = start_pos + 1; i < a.length; i++) {
- if (a[start_pos] > a[i]) {
- next_pos++;
- }
- }
- if (next_pos == start_pos) {
- continue;
- }
- while (a[next_pos] == a[start_pos]) {
- next_pos++;
- }
- while (true) {
- int tmp_ele = a[next_pos];
- a[next_pos] = a[start_pos];
- next_pos = start_pos;
- for (int i = start_pos + 1; i < a.length; i++) {
- if (tmp_ele > a[i]) {
- next_pos++;
- }
- }
- if (next_pos == start_pos) {
- a[start_pos] = tmp_ele;
- break;
- }
- while (a[next_pos] == a[start_pos]) {
- next_pos++;
- }
- }
- }
- }