-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSortingUtils.java
More file actions
70 lines (59 loc) · 1.74 KB
/
SortingUtils.java
File metadata and controls
70 lines (59 loc) · 1.74 KB
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
67
68
69
70
package com.dsj.sorting;
import java.util.Arrays;
import java.util.Scanner;
public abstract class SortingUtils {
int sizeOfArr;
boolean dataTypeNumber = false;
Object[] unsortedArr;
Scanner sc;
/** Take the size of the input and initialize the unsorted array. */
SortingUtils() {
System.out.println("Enter the size of your list:");
sc = new Scanner(System.in);
this.sizeOfArr = sc.nextInt();
initializeUnsortedArr();
}
/**
* Depending on the input provided, the sorting algorithm will sort the inputs.
* If a number is provided it sorts the number based on their value. If the
* input is anything but a number, it sorts based on its length.
*/
void initializeUnsortedArr() {
System.out.println("Enter your items:");
String typeTestVar = sc.next();
if (isOfTypeNumber(typeTestVar)) {
dataTypeNumber = true;
unsortedArr = new Number[sizeOfArr];
unsortedArr[0] = Double.parseDouble(typeTestVar);
for (int i = 1; i < sizeOfArr; i++) {
unsortedArr[i] = sc.nextDouble();
}
} else {
unsortedArr = new String[sizeOfArr];
unsortedArr[0] = typeTestVar;
for (int i = 1; i < sizeOfArr; i++) {
unsortedArr[i] = sc.next();
}
}
sc.close();
}
private boolean isOfTypeNumber(String typeTestVar) {
return typeTestVar.matches("^[-\\+]?\\d*.?\\d+$");
}
public void display() {
System.out.println("The sorted array is: ");
Arrays.stream(unsortedArr).forEach(System.out::println);
}
public void sort() {
if (!dataTypeNumber) {
this.sortArrayOfStrings();
} else {
this.sortArrayOfNumbers();
}
}
/**
* To be implemented by each sorting class.
*/
abstract void sortArrayOfNumbers();
abstract void sortArrayOfStrings();
}