-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathQuestion1.java
66 lines (49 loc) · 1.82 KB
/
Question1.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
63
64
65
66
package com.iamoperand.RandomQuestions;
import java.util.Scanner;
/**
* Created by iamoperand on 16/7/17.
*/
public class Question1 {
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
System.out.println("What is the size of the array?");
int size = scanner.nextInt();
int[] valueArray = new int[size];
int[] indexArray = new int[size];
System.out.println("Enter the values of the array...");
for(int i=0; i<size; i++){
valueArray[i] = scanner.nextInt();
}
System.out.println("Enter the corresponding positions in the index array...");
for(int i=0; i<size; i++){
indexArray[i] = scanner.nextInt();
}
/*
I have used the implementation of Insertion Sort here.
If you want to decrease the time your algorithm takes, then you can use the implementation of Quick Sort here.
*/
for(int i=1; i<size; i++){
int indexKey = indexArray[i];
int valueKey = valueArray[i];
int j = i-1;
while(j>=0 && indexArray[j]>indexKey){
indexArray[j+1] = indexArray[j];
valueArray[j+1] = valueArray[j];
j--;
}
indexArray[j+1] = indexKey;
valueArray[j+1] = valueKey;
}
//Print the 2 sorted arrays for inspection
System.out.println("The sorted valueArray is");
for(int i=0; i<size; i++){
System.out.print(valueArray[i] + " ");
}
System.out.println();
System.out.println("The sorted indexArray is");
for(int i=0; i<size; i++){
System.out.print(indexArray[i] + " ");
}
System.out.println();
}
}