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