-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathselectionSort.java
More file actions
89 lines (86 loc) · 2.89 KB
/
Copy pathselectionSort.java
File metadata and controls
89 lines (86 loc) · 2.89 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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
public class selectionSort{
private int[] array;
// public static final boolean defaultFlag = false; // provide default value to the inSort method
public selectionSort(int[] array){
this.array = array; // constructor
}
public void seSort(boolean reverse){
// use a boolean variable named reverse to control whether to reverse sort or not
int minIndex;
for(int i=0; i<this.array.length-1; i++){
minIndex = i;
for(int j=i+1; j<this.array.length; j++){
if(!reverse){ // use the boolean here
if(this.array[j]<this.array[minIndex]) {
minIndex = j;
}
}
else {
if(this.array[j]>this.array[minIndex]){
minIndex = j;
}
}
}
// swap the values
int temp = this.array[i];
this.array[i] = this.array[minIndex];
this.array[minIndex] = temp;
}
}
public void seSort(){
// overload the inSort() method, setting the 'default' sort order to asc
// seSort(defaultFlag);
seSort(false);
}
// public void seSortReverse(){
// int minIndex;
// for(int i=0; i<this.array.length-1; i++){
// minIndex = i;
// for(int j=i+1;j<this.array.length; j++){
// if(this.array[j] > this.array[minIndex]){
// minIndex = j;
// }
// }
// // swap the values
// int temp = this.array[i];
// this.array[i] = this.array[minIndex];
// this.array[minIndex] = temp;
// }
// }
// public static void swap(int[] array, int index1, int index2){
// int temp = array[index1];
// array[index1] = array[index2];
// array[index2] = temp;
// }
public static void main(String[] args){
int[] numbers = {8, 3, 7, 10, 9, 10, 20, 1};
// create the object
selectionSort x = new selectionSort(numbers);
// print out the original object/ array
for (int item: numbers) {
System.out.print(item+", ");
}
System.out.print("\n");
boolean reverse = false;
// call the seSort() method on the object
x.seSort(); // default sort
for (int i:x.array){
System.out.print(i+", ");
}
System.out.print("\n");
reverse = true;
// call the seSort() with a reverse value
x.seSort(reverse);
for (int i: x.array){
System.out.print(i+", ");
}
System.out.print("\n");
reverse = false;
// test method overloading
x.seSort(reverse);
for (int i: x.array){
System.out.print(i+", ");
}
System.out.print("\n");
}
}