This repository was archived by the owner on Mar 3, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSelectionSort.java
More file actions
90 lines (85 loc) · 1.66 KB
/
SelectionSort.java
File metadata and controls
90 lines (85 loc) · 1.66 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
90
public class SelectionSort implements Sort
{
//private data members
private sortParams sParams;
//constructors
public SelectionSort()
{
sParams = null;
}
//initializer method
public void initialize(sortParams s)
{
sParams = s;
}
//getter
public sortParams getSortParams()
{
return sParams;
}
void TestPeakUsage(int memUsage)
{
if(memUsage > sParams.getMemUsage())
{
sParams.setMemUsage(memUsage);
}
}
/*
* Selection Sort Methods for Ascending/Descending
* (Logic for the sorting)
*/
void SelSort(int[] arr, int start, int end, Direction dir)
{
int memUsage = 0;
memUsage += 32;
TestPeakUsage(memUsage);
int nextPos = start;
while(nextPos<end)
{
memUsage += 32;
TestPeakUsage(memUsage);
int minElementSoFar = nextPos;
memUsage += 32;
TestPeakUsage(memUsage);
if(dir == Direction.ASCENDING)
{
for(int i = nextPos+1; i<end; ++i)
{
if(arr[i]<arr[minElementSoFar])
{
minElementSoFar = i;
}
}
}
else
{
for(int i = nextPos+1; i<end; ++i)
{
if(arr[i]>arr[minElementSoFar])
{
minElementSoFar = i;
}
}
}
memUsage -= 32;
memUsage += 32;
TestPeakUsage(memUsage);
int temp = arr[nextPos];
arr[nextPos] = arr[minElementSoFar];
arr[minElementSoFar] = temp;
++nextPos;
memUsage -= 64;
}
memUsage -= 32;
}
/*
* Sort Method Implementation
* sorts in order the input has using the private SelSort
* methods above
*/
public void sort(sortParams sParams)
{
SelSort(sParams.getArray(), sParams.getStartIndex(), sParams.getEndIndex(), sParams.getDirection());
this.sParams.setArray(sParams.getArray());
}
}