Skip to content

Commit d7fcdf4

Browse files
Merge pull request TheAlgorithms#284 from honeycoder96/patch-1
Create cyclesort.java
2 parents 4d0d02d + 6806fa6 commit d7fcdf4

File tree

1 file changed

+78
-0
lines changed

1 file changed

+78
-0
lines changed

Sorts/cyclesort.java

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
import java.util.*;
2+
import java.lang.*;
3+
4+
class Sorting
5+
{
6+
// Function that sort the array using Cycle sort
7+
public static void cycleSort (int arr[], int n)
8+
{
9+
// count number of memory writes
10+
int writes = 0;
11+
12+
// traverse array elements
13+
for (int cycle_start=0; cycle_start<=n-2; cycle_start++)
14+
{
15+
// initialize item as starting point
16+
int item = arr[cycle_start];
17+
18+
// Find position where we put the item.
19+
int pos = cycle_start;
20+
for (int i = cycle_start+1; i<n; i++)
21+
if (arr[i] < item)
22+
pos++;
23+
24+
// If item is already in correct position
25+
if (pos == cycle_start)
26+
continue;
27+
28+
// ignore all duplicate elements
29+
while (item == arr[pos])
30+
pos += 1;
31+
32+
// put the item to it's right position
33+
if (pos != cycle_start)
34+
{
35+
int temp = item;
36+
item = arr[pos];
37+
arr[pos] = temp;
38+
writes++;
39+
}
40+
41+
// Rotate rest of the cycle
42+
while (pos != cycle_start)
43+
{
44+
pos = cycle_start;
45+
46+
// Find position where we put the element
47+
for (int i = cycle_start+1; i<n; i++)
48+
if (arr[i] < item)
49+
pos += 1;
50+
51+
// ignore all duplicate elements
52+
while (item == arr[pos])
53+
pos += 1;
54+
55+
// put the item to it's right position
56+
if (item != arr[pos])
57+
{
58+
int temp = item;
59+
item = arr[pos];
60+
arr[pos] = temp;
61+
writes++;
62+
}
63+
}
64+
}
65+
}
66+
67+
// main program to test above function
68+
public static void main(String[] args)
69+
{
70+
int arr[] = {1, 8, 3, 9, 10, 10, 2, 4 };
71+
int n = arr.length;
72+
cycleSort(arr, n) ;
73+
74+
System.out.println("After sort : ");
75+
for (int i =0; i<n; i++)
76+
System.out.print(arr[i] + " ");
77+
}
78+
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy