Skip to content

Commit c64241c

Browse files
authored
Create CyclicSort.java
1 parent fa84e4c commit c64241c

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed

CyclicSort.java

+62
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
import java.util.*;
2+
public class CycleSort{
3+
public static int[] rotate(int position,int element,int array[],int strt){
4+
while (position != strt)
5+
{
6+
position = strt;
7+
for (int i = strt+1; i<array.length; i++)
8+
if (array[i] < element)
9+
position += 1;
10+
while(element == array[position])
11+
position += 1;
12+
if(element != array[position])
13+
{
14+
int temp = element;
15+
element = array[position];
16+
array[position] = temp;
17+
}
18+
}
19+
return array;
20+
}
21+
22+
public static void main(String args[]){
23+
Scanner in = new Scanner(System.in);
24+
System.out.println("Enter the number of elements you want to add : ");
25+
int n=in.nextInt();
26+
System.out.println("Enter all the elements : ");
27+
int a[]=new int[n];
28+
for(int i=0;i<n;i++){
29+
a[i]=in.nextInt();
30+
}
31+
32+
System.out.print("Before Sorting : ");
33+
for (int i =0; i<n; i++)
34+
System.out.print(a[i] + " ");
35+
36+
System.out.println();
37+
int writes = 0;
38+
for (int strt=0; strt<=n-2; strt++)
39+
{
40+
int element = a[strt];
41+
int position = strt;
42+
for (int i = strt+1; i<n; i++)
43+
if (a[i] < element)
44+
position++;
45+
46+
if (position == strt)
47+
continue;
48+
while (element == a[position])
49+
position += 1;
50+
if (position != strt)
51+
{
52+
int temp = element;
53+
element = a[position];
54+
a[position] = temp;
55+
}
56+
rotate( position, element, a, strt);
57+
System.out.print("After Sorting : ");
58+
for (int i =0; i<n; i++)
59+
System.out.print(a[i] + " ");
60+
}
61+
}
62+
}

0 commit comments

Comments
 (0)