-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSelectionSort.java
More file actions
108 lines (88 loc) · 3.06 KB
/
SelectionSort.java
File metadata and controls
108 lines (88 loc) · 3.06 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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
package com.yijie.sort;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
public class SelectionSort {
public static void main(String[] args) {
//Test
//int[] arr = {101, 34,119, 1};
//create a array with 80000 random numbers
int[] arr = new int[80000];
for (int i = 0; i < arr.length; i++) {
arr[i] = (int) (Math.random() * 80000);
}
//System.out.println("array before selection sort is: " + Arrays.toString(arr));
//time before sort
Date date1 = new Date();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String date1Str = simpleDateFormat.format(date1);
System.out.println("time before bubble sort: " + date1Str);
selectionSort(arr);
//time after sort
Date date2 = new Date();
String date2Str = simpleDateFormat.format(date2);
System.out.println("time after bubble sort: " + date2Str);
}
//Selection sort
public static void selectionSort(int[] arr) {
int minIndex;
int min;
for (int i = 0; i < arr.length - 1; i++) {
minIndex = i;
min = arr[minIndex];
for (int j = 0 + i + 1; j < arr.length; j++) {
if (arr[j] < min) {
min = arr[j];//Reset min and minIndex
minIndex = j;
}
}
//swap the smallest number to the first position
if (minIndex != i) {
arr[minIndex] = arr[i];
arr[i] = min;
}
//System.out.printf("array after iteration %d: " + Arrays.toString(arr) + "\n", i + 1);
}
/*
//Iteration 1
int minIndex = 0;
int min = arr[0];
for (int j = 0 + 1; j < arr.length; j++){
if (arr[j] < min){
min = arr[j];//Reset min and minIndex
minIndex = j;
}
}
//swap the smallest number to the first position
arr[minIndex] = arr[0];
arr[0] = min;
System.out.println("array after iteration 1: " + Arrays.toString(arr));
//Iteration 2
minIndex = 1;
min = arr[1];
for (int j = 0 + 2; j < arr.length; j++){
if (arr[j] < min){
min = arr[j];//Reset min and minIndex
minIndex = j;
}
}
//swap the smallest number to the first position
arr[minIndex] = arr[1];
arr[1] = min;
System.out.println("array after iteration 1: " + Arrays.toString(arr));
//Iteration 3
minIndex = 2;
min = arr[2];
for (int j = 0 + 3; j < arr.length; j++){
if (arr[j] < min){
min = arr[j];//Reset min and minIndex
minIndex = j;
}
}
//swap the smallest number to the first position
arr[minIndex] = arr[2];
arr[2] = min;
System.out.println("array after iteration 1: " + Arrays.toString(arr));
*/
}
}