-
Notifications
You must be signed in to change notification settings - Fork 41
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #63 from HarshVR1947/main
Cyclic Sort code in Java
- Loading branch information
Showing
1 changed file
with
27 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,27 @@ | ||
// Online Java Compiler | ||
// Use this editor to write, compile and run your Java code online | ||
import java.util.Arrays; | ||
|
||
class Cyclesort{ | ||
public static void main(String[] args) { | ||
int[] arr={3,5,2,1,4}; | ||
cyclicsort(arr); | ||
System.out.println(Arrays.toString(arr)); | ||
} | ||
static void cyclicsort(int[] arr){ | ||
int i=0; | ||
while(i<arr.length){ | ||
int correct=arr[i]-1; | ||
if(arr[i]!=correct){ | ||
swap(arr,i,correct); | ||
}else{ | ||
i++; | ||
} | ||
} | ||
} | ||
static void swap(int[] arr,int first, int second){ | ||
int temp=arr[first]; | ||
arr[first]=arr[second]; | ||
arr[second]=temp; | ||
} | ||
} |