Skip to content

Commit 1379842

Browse files
Merge pull request #91 from MohammedHassan07/cyclic
Cyclic sort solution is added
2 parents 4824e57 + 7e308d3 commit 1379842

1 file changed

Lines changed: 41 additions & 0 deletions

File tree

Sorting/CyclicSort.java

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
import java.util.Arrays;
2+
3+
public class CyclicSort {
4+
public static void main(String[] args) {
5+
6+
// Question: Sort the array if the numbers are given from 1 to n, where n is
7+
// the length of the array. remember array should be continuous.
8+
// TimeComplexity: O(number of comparison).
9+
// SpaceComplexity: O(1).
10+
11+
int[] arr = {5, 2, 3, 1, 7, 6, 4}; // Declaration and initialization of unsorted array
12+
13+
System.out.println(Arrays.toString(cyclicSort(arr))); // Function call and printing the sorted array.
14+
}
15+
16+
// Method to sort the array
17+
public static int[] cyclicSort(int[] arr) {
18+
19+
int i = 0;
20+
while(i < arr.length){
21+
22+
int correctIndex = arr[i] - 1;
23+
if(arr[i] != arr[correctIndex]) {
24+
25+
swap(arr, i, correctIndex); // Function call to swap the number.
26+
}else {
27+
28+
i++;
29+
}
30+
}
31+
return arr;
32+
}
33+
34+
// Function to swap the array.
35+
public static void swap(int[] arr, int first, int second) {
36+
37+
int temp = arr[first];
38+
arr[first] = arr[second];
39+
arr[second] = temp;
40+
}
41+
}

0 commit comments

Comments
 (0)