-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathRearrangeAnArray.java
More file actions
48 lines (41 loc) · 1018 Bytes
/
RearrangeAnArray.java
File metadata and controls
48 lines (41 loc) · 1018 Bytes
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
import java.util.Scanner;
class RearrangeAnArray {
public static void main(String[] args) {
RearrangeAnArray ob = new RearrangeAnArray();
int t, n, i;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of test cases: ");
t = sc.nextInt();
while( t != 0) {
System.out.println("Enter the size of array: ");
n = sc.nextInt();
int[] arr = new int[n];
System.out.println("Enter the array: ");
for( i = 0; i < n; i++ ) {
arr[i] = sc.nextInt();
}
ob.rearrangeAnArray( arr, n );
t--;
}
sc.close();
}
void rearrangeAnArray( int[] arr, int n ) {
int next = 0, temp, i;
temp = arr[0];
while( next != 0 ) {
if( arr[next] == 0 ) {
arr[next] = temp;
System.out.printf("arr[%d] = %d", arr[next], temp);
}
else {
arr[next] = arr[arr[next]];
System.out.printf("arr[%d] = %d", arr[next], arr[arr[next]]);
}
next = arr[next];
}
//Printing the array
for( i = 0; i < n; i++ ) {
System.out.print(arr[i]+" ");
}
}
}