-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSelectionSortRecursion.java
74 lines (58 loc) · 1.69 KB
/
SelectionSortRecursion.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
67
68
69
70
71
72
73
74
package projectCode20280;
import java.util.Arrays;
public class SelectionSortRecursion
{
public static <E extends Comparable<E>> void selectionSort(E[] arr, int i)
{
if (i >= arr.length - 1)
{
return;
}
int minIndex = i;
for (int index = i + 1; index < arr.length; index++)
{
if (arr[index].compareTo(arr[minIndex]) < 0 )
{
minIndex = index;
}
}
E temp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = temp;
selectionSort(arr, i + 1);
}
public static <E extends Comparable<E>> void sort(E[] arr)
{
int n = arr.length;
// One by one move boundary of unsorted subarray
for (int i = 0; i < n-1; i++)
{
// Find the minimum element in unsorted array
int min_idx = i;
for (int j = i+1; j < n; j++)
if (arr[j].compareTo(arr[min_idx]) < 0)
min_idx = j;
// Swap the found minimum element with the first
// element
E temp = arr[min_idx];
arr[min_idx] = arr[i];
arr[i] = temp;
}
}
public static void main(String[] args)
{
int size = 1000;
Integer[] anArray = new Integer[size];
for (int i = 0; i < size; i++)
{
anArray[i] = (int) (Math.random() * (1000 - 1)) + 1;
}
System.out.println("Before sorting :\n" + Arrays.toString(anArray));
long startTime = System.currentTimeMillis();
sort(anArray);
long endTime = System.currentTimeMillis();
long timeTaken = endTime - startTime;
System.out.println("After sorting :\n" + Arrays.toString(anArray));
System.out.println("Time taken to sort (in milli seconds): " + timeTaken);
}
}